Created
September 8, 2024 16:15
-
-
Save phillipharding/29c46d3eb6928dce2cedef433cede83b to your computer and use it in GitHub Desktop.
Array Element Moving
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
a=[ | |
{ sortIdx: 5, value: "E"}, | |
{ sortIdx: 6, value: "F"}, | |
{ sortIdx: 1, value: "A"}, | |
{ sortIdx: 4, value: "D"}, | |
{ sortIdx: 3, value: "C"}, | |
{ sortIdx: 2, value: "B"}, | |
]; | |
function move(elToMove, targetSortIdx) { | |
b = structuredClone(a); | |
targetIdx = b.findIndex((v) => v.sortIdx === targetSortIdx); | |
if (targetIdx < 0) return; | |
elToMoveIdx = b.findIndex((v) => v.sortIdx === elToMove.sortIdx); | |
if (targetIdx < 0) return; | |
b.splice(elToMoveIdx, 1); | |
b.splice(targetIdx, 0, elToMove); | |
newIdx = 0; | |
b.forEach((v) => v.sortIdx = ++newIdx); | |
return b; | |
} | |
a.sort((a, b) => (a.sortIdx < b.sortIdx) ? -1 : (a.sortIdx < b.sortIdx) ? 1 : 0 ); | |
console.clear(); | |
console.log(a); | |
b = move(a[5], 3); | |
console.log(b); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment