I am a bit stuck with this problem. I am trying to write a function that takes an index and moves the item with that index in an array to the first position while maintaining the subsequential order of the other items.
const unorderedArr = [item1, item2, item3, item4]
const reorderArr = (i, arr) => {
...
}
const reorderedArr = reorderArr(2, unorderedArr)
// [item3, item4, item1, item2]
Happy for any pointers!
>Solution :
You could use a swapping with the previous item until the index is zero.
const
reorderArr = (array, i) => {
while (i) {
[array[i], array[i - 1]] = [array[i - 1], array[i]];
i--;
}
return array;
};
console.log(...reorderArr(['item1', 'item2', 'item3', 'item4'], 2));