Skip to content

Instantly share code, notes, and snippets.

@phillipharding
Created September 8, 2024 16:15
Show Gist options
  • Save phillipharding/29c46d3eb6928dce2cedef433cede83b to your computer and use it in GitHub Desktop.
Save phillipharding/29c46d3eb6928dce2cedef433cede83b to your computer and use it in GitHub Desktop.
Array Element Moving
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