I found a great function for moving elements in an array to different positions:
function eleMove1( arr, from, to ) {
arr.splice( to, 0, arr.splice( from, 1 )[ 0 ] );
}
var arr = [ 'a', 'b', 'c', 'd', 'e' ];
eleMove1( arr, 3, 0 );
console.log ( 'eleMove1: ' + arr ); // eleMove1: d,a,b,c,e
console.log ( arr ); // ["d", "a", "b", "c", "e"]
console.log ( '\n ' );
/*
*/
function eleMove2( arr, from, to ) {
arr.splice( to, 0, arr.splice( from, 1 ) );
}
var arr = [ 'a', 'b', 'c', 'd', 'e' ];
eleMove2( arr, 3, 0 );
console.log ( 'eleMove2: ' + arr ); // eleMove2: d,a,b,c,e
console.log ( arr ); // [["d"], "a", "b", "c", "e"]
console.log ( '\n ' );
But as I am just getting started with JS I am puzzled as to the relevance of the [ 0 ] );
part of the splice statement. Convention leads me to believe it refers to the first indexed element of an array. But what array? Surely not the arr passed to the function, and surely not the func's arg's array, since the original function I lifted this from didn't actually pass the arr as one of the func's args:
Move an array element from one array position to another
It seems to be hanging off the end of the second splice call on the arr, but I still can't figure out why and what for.
The arr's output does, however, seems largely unaffected by the absence of this little piece of code. What then is the significance of this little snippet in the splice statement, and how does it lend relevance to the overall performance of the function, if at all?