Created
January 8, 2019 10:41
-
-
Save ali-master/0f53aceaf43d026aafe6dc0acf88586d to your computer and use it in GitHub Desktop.
Moves an array item from one position in an array to another.
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
/* #move - Moves an array item from one position in an array to another. | |
Note: This is a pure function so a new array will be returned, instead | |
of altering the array argument. | |
Arguments: | |
1. array (String) : Array in which to move an item. (required) | |
2. moveIndex (Object) : The index of the item to move. (required) | |
3. toIndex (Object) : The index to move item at moveIndex to. (required) | |
*/ | |
function move(array, moveIndex, toIndex) { | |
let item = array[moveIndex] | |
let length = array.length | |
let diff = moveIndex - toIndex | |
if (diff > 0) { | |
// move left | |
return [ | |
...array.slice(0, toIndex), | |
item, | |
...array.slice(toIndex, moveIndex), | |
...array.slice(moveIndex + 1, length), | |
] | |
} else if (diff < 0) { | |
// move right | |
return [ | |
...array.slice(0, moveIndex), | |
...array.slice(moveIndex + 1, toIndex + 1), | |
item, | |
...array.slice(toIndex + 1, length), | |
] | |
} | |
return array | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment