Created
November 13, 2020 16:19
-
-
Save davidsharp/13c506aa246c643bda5af053526eb263 to your computer and use it in GitHub Desktop.
move an item in an array up or down by an amount
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 reorder = (array, index, moveBy) => { | |
| let temp = array.map((c,i)=>([c,i])) | |
| temp[index][1]=temp[index][1]+moveBy+(moveBy>0?.5:-.5) | |
| return temp.sort((a,b)=>a[1]-b[1]).map(c=>c[0]) | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Works like
reorder([1,2,3,4,5],2,-1)=>[ 1, 3, 2, 4, 5 ]Limits an items maximum movement to the the top or bottom (ie, no overflow/underflow) "for free"