Last active
August 29, 2015 14:07
-
-
Save mteece/e14812e5204236753359 to your computer and use it in GitHub Desktop.
Move an item in array to a position.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
moveTo = function (arr, value, position) { | |
var index = arr.indexOf(value), newPos = position - 1, temp = arr[newPos]; | |
if (index === -1) return; | |
if (newPos >= arr.length || newPos < 0) return; | |
if (index === newPos) return; | |
arr.splice(newPos, 1, value); // Remove 1 item at newPos insert value | |
arr.splice(index, 1, temp); // Remove 1 item at index, insert temp | |
} | |
//var a = ['Matt', 'Ralph', 'Jason']; | |
//var a = [{name:'Matt'}, {name:'Ralph'}, {name:'Jason'}]; | |
//1,2,3 non zero based | |
//moveTo(a, a[0], 2); | |
//moveTo(a, a[1], 2); //move ralph to pos 2 | |
//moveTo(a, a[2], 1); //move jason to pos 1 | |
//moveTo(a, a[0], 3); //move matt to pos 3 | |
//console.dir(a); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment