Last active
December 20, 2022 14:48
-
-
Save freddi301/3290a34342b0c4db61f1b29308461d40 to your computer and use it in GitHub Desktop.
Move item in array for drag drop reordering
This file contains 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
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