Skip to content

Instantly share code, notes, and snippets.

@freddi301
Last active December 20, 2022 14:48
Show Gist options
  • Save freddi301/3290a34342b0c4db61f1b29308461d40 to your computer and use it in GitHub Desktop.
Save freddi301/3290a34342b0c4db61f1b29308461d40 to your computer and use it in GitHub Desktop.
Move item in array for drag drop reordering
function moveItem<T>(fromIndex: number, toIndex: number, array: Array<T>): Array<T> {
if (fromIndex < toIndex) {
return [...array.slice(0, fromIndex), ...array.slice(fromIndex + 1, toIndex + 1), array[fromIndex], ...array.slice(toIndex + 1)];
}
if (fromIndex > toIndex) {
return [...array.slice(0, toIndex), array[fromIndex], ...array.slice(toIndex, fromIndex), ...array.slice(fromIndex + 1)];
}
return array;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment