Skip to content

Instantly share code, notes, and snippets.

@ali-master
Created January 8, 2019 10:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ali-master/0f53aceaf43d026aafe6dc0acf88586d to your computer and use it in GitHub Desktop.
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.
/* #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