Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Move item to first position in array but keep order

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading