Move array item to the beginning of its array in JavaScript

OpenJavaScript 0

Last updated: December 13, 2023.

An item in an array can be moved to its beginning by:

  1. Checking if item exists in the array (to prevent an unhandled error)
  2. Filtering the array of that value
  3. Inserting the item at the beginning of the array

Here is an example in code:

const array = ["Second", "Third", "First"];

// Check if a value exists...
if (array.includes("First")) {

    //...filter this value from the array...
    const arrayFiltered = array.filter((val) => val !== "First");

    //...and place it first in a new array, spreading the other values afterwards
    const res = ["First", ...arrayFiltered];

    console.log(res); // [ "First", "Second", "Third" ]

};

Spreading into a new array is preferred above over unshift() because it doesn't 'mutate' (i.e. modify) the array passed into it (generally considered bad practice).

Though it works, the value of the array item to be moved is repeated in many places and the code is not reusable.

Both issues can be solved by adapting the code to be used inside a standalone function:

function itemToArrayStart(item, array) {
    
    if (array.includes(item)) {

        const arrayFiltered = array.filter((val) => val !== item);

        const res = [item, ...arrayFiltered];

        return res;

    } else {

        console.error(`No item ${item} in array`);

    };
}

itemToArrayStart("First", array); // [ "First", "Second", "Third" ]
itemToArrayStart("Second", array); // [ "Second", "Third", "First" ]
itemToArrayStart("Fourth", array); // Logs error: "No item Fourth in array"

Tags: