Reputation: 515
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?
Upvotes: 4
Views: 51
Reputation: 6075
The [0]
refers to the first element in the array that is deleted. If we walk through the code.
function eleMove1( arr, from, to ) {
arr.splice( to, 0, arr.splice( from, 1 )[ 0 ] );
}
Would be similar to writing like this.
function eleMove1( arr, from, to ) {
deletedItemsArray = arr.splice( from, 1 );
itemYouDeleted = deletedItemsArray[0];
arr.splice( to, 0, itemYouDeleted);
}
This works because splice mutates arr in place and returns the items it deletes as an array. That deleted item becomes an argument to the initial arr.splice method, which puts itemYouDeleted
at position to
Upvotes: 4
Reputation: 50787
Your outputs do show the difference that this code makes.
orig: console.log ( arr ); // ["d", "a", "b", "c", "e"]
changed: console.log ( arr ); // [["d"], "a", "b", "c", "e"]
^^^^^
That little [0]
grabbed the first element from the array returned by splice
and used it rather than the whole array when you do the insert.
Upvotes: 1