Last active
September 28, 2022 07:15
-
-
Save foyez/f6afb78897542cceb3807faacbc84f02 to your computer and use it in GitHub Desktop.
Move an array element from one position to another
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
| // Move array element using splice where time complexity is Quadratic Time - O(n^2) | |
| function arrayMove(arr, oldIndex, newIndex) { | |
| const copiedArr = [...arr]; | |
| const length = copiedArr.length; | |
| if (oldIndex !== newIndex && length > oldIndex && length > newIndex) { | |
| copiedArr.splice(newIndex, 0, copiedArr.splice(oldIndex, 1)[0]); | |
| } | |
| return copiedArr; | |
| } | |
| // Move array element using flatMap where time complexity is Linear Time - O(n) | |
| function arrayMove(arr, oldIndex, newIndex) { | |
| const length = arr.length; | |
| const itemToMove = arr[oldIndex] | |
| if (oldIndex === newIndex || oldIndex > length || newIndex > length) { | |
| return arr; | |
| } | |
| return arr.flatMap((item, index) => { | |
| if (index === oldIndex) return []; | |
| if (index === newIndex) return oldIndex < newIndex ? [item, itemToMove] : [itemToMove, item]; | |
| return item; | |
| }) | |
| } | |
| // Move array element using reduce where time complexity is Linear Time - O(n) | |
| function arrayMove(arr, oldIndex, newIndex) { | |
| const length = arr.length; | |
| const itemToMove = arr[oldIndex] | |
| if (oldIndex === newIndex || oldIndex > length || newIndex > length) { | |
| return arr; | |
| } | |
| return arr.reduce((acc, item, index) => { | |
| if (index === oldIndex) return acc; | |
| if (index === newIndex) return oldIndex < newIndex ? [...acc, item, itemToMove] : [...acc, itemToMove, item]; | |
| return [...acc, item]; | |
| }, []) | |
| } | |
| arrayMove([1,2,3,4], 0, 3) // [2,3,4,1] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment