Home > Software design >  Move item to first position in array but keep order
Move item to first position in array but keep order

Time:03-18

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!

CodePudding user response:

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));

CodePudding user response:

Simply you can do like this

const unorderedArr = ["item1", "item2", "item3", "item4"];
const reorderArr = (i, arr) => {
  const movingElement = arr[i]; // get the element at index i
  arr.splice(i, 1); // remove the element from index i next to one ( item 3)
  arr.unshift(movingElement); // add the element to the beginning of the array
  return arr;
};

const reorderedArr = reorderArr(2, unorderedArr);
console.log("reorderedArr", reorderedArr);
//  [ 'item3', 'item1', 'item2', 'item4' ]

CodePudding user response:

slice(i) method will return an array after index(inceluded), and slice(0, i) will return an array from beginig of array to index (excluded). So result will be: ["item3","item4","item1","item2"]

const unorderedArr = ['item1', 'item2', 'item3', 'item4']
const reorderArr = (i, arr) => { 
  return [...arr.slice(i), ...arr.slice(0,i)];
}

const reorderedArr = reorderArr(2, unorderedArr);
console.log(reorderedArr)

  • Related