Skip to content

Instantly share code, notes, and snippets.

@davidsharp
Created November 13, 2020 16:19
Show Gist options
  • Select an option

  • Save davidsharp/13c506aa246c643bda5af053526eb263 to your computer and use it in GitHub Desktop.

Select an option

Save davidsharp/13c506aa246c643bda5af053526eb263 to your computer and use it in GitHub Desktop.
move an item in an array up or down by an amount
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])
}
@davidsharp

Copy link
Copy Markdown
Author

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"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment