ArticleZip > Javascript Move An Item Of An Array To The Front

Javascript Move An Item Of An Array To The Front

Are you looking to level up your JavaScript skills? One neat trick you might find useful is moving an item of an array to the front. This can come in handy in various scenarios where you need to prioritize certain elements within your array. In this guide, we'll show you a simple and efficient way to accomplish this task using JavaScript.

To begin with, let's consider an array called `myArray` that contains some sample elements:

Javascript

let myArray = [1, 2, 3, 4, 5];

Now, say you want to move a specific element to the front of the array. Let's say we want to move the element with the value `3` to the front. Here's how you can do it:

Javascript

function moveItemToFront(array, item) {
    const index = array.indexOf(item);

    if (index > -1) {
        array.splice(index, 1); // Remove the item from its current position
        array.unshift(item); // Add the item to the beginning of the array
    }

    return array;
}

let itemToMove = 3;
let newArray = moveItemToFront(myArray, itemToMove);

console.log(newArray); // Output: [3, 1, 2, 4, 5]

In the `moveItemToFront` function, we first find the index of the item we want to move using the `indexOf` method. If the item is found (i.e., its index is greater than -1), we remove it using `splice` and then add it to the front of the array using `unshift`. Finally, we return the modified array.

This simple function allows you to move any item within an array to the front effortlessly. You can customize it further based on your specific requirements.

It's worth noting that this method modifies the original array. If you prefer not to alter the original array and instead create a new array with the updated order, you can make a slight modification to the function:

Javascript

function moveItemToFront(array, item) {
    const index = array.indexOf(item);

    if (index > -1) {
        let newArray = [...array]; // Create a copy of the original array
        newArray.splice(index, 1);
        newArray.unshift(item);
        return newArray; // Return the modified array
    }

    return array;
}

By using the spread operator (`[...array]`), we create a shallow copy of the original array, preserving the original array intact.

In conclusion, moving an item to the front of an array in JavaScript is a handy technique that can help you manage your data more efficiently. With the simple function provided in this guide, you can easily manipulate the order of elements within an array to suit your needs. Experiment with different scenarios and have fun mastering this useful JavaScript skill!