Created
May 16, 2017 14:47
-
-
Save dmmarmol/15fa9ccd698245e08704a3ed470382cf to your computer and use it in GitHub Desktop.
Move items inside an array and reorder (ES6)
This file contains hidden or 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
const arrayMove = (array, from, to) => { | |
// Clone the original array | |
let newArray = array.slice(); | |
// Get the item that will be moved | |
const movingItem = newArray.splice(from, 1)[0]; | |
// Replace that item in the 'to' position | |
newArray.splice(to, 0, movingItem); | |
return newArray; | |
}; | |
// Example | |
// arrayMove([1,2,3,4], 3, 0); | |
// Result | |
// [4,2,3,1] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment