DEV Community

Avnish
Avnish

Posted on

Moving an Item to the Last Position in an Array in JavaScript

In JavaScript, arrays are dynamic collections that allow you to store and manipulate data. Sometimes, you may need to move an item to the last position in an array. This is a common operation, and there are multiple ways to achieve it. In this article, we will discuss how to move an item to the last position of an array, covering both simple and optimized solutions.


Approach 1: Using splice() and push()

One of the most efficient and concise ways to move an item to the last position is by combining splice() and push() methods. Here's how:

How It Works:

  • splice(index, 1): The splice() method removes the element at the specified index. It returns an array of the removed elements, and by using [0], we can access the first (and only) element.
  • push(): The push() method adds an item to the end of the array.

By using splice() to remove the element and push() to add it back to the end, we can achieve the task in one clean line of code.

Code Example:

function moveToLast(arr, item) {
    // Find the index of the item, remove it, and push it to the end
    arr.push(arr.splice(arr.indexOf(item), 1)[0]);
    return arr;
}

// Example array
let arr = [1, 2, 3, 4, 5];
let itemToMove = 3;

// Move item to last position
arr = moveToLast(arr, itemToMove);

console.log(arr);  // Output: [1, 2, 4, 5, 3]
Enter fullscreen mode Exit fullscreen mode

Explanation:

  1. arr.indexOf(item): Finds the index of the specified item in the array.
  2. arr.splice(arr.indexOf(item), 1): Removes the item at the found index and returns an array containing that item.
  3. [0]: Since splice() returns an array of removed elements, we use [0] to get the first (and only) item from the array.
  4. arr.push(...): Adds the item to the end of the array.

This method is elegant and effective, especially when you only know the item and not its index in advance.


Approach 2: Using splice() and push() Separately (If You Know the Index)

In some cases, you may already know the index of the item. In such situations, you can simplify the process by separating the splice() and push() operations.

Code Example:

function moveToLast(arr, item) {
    const index = arr.indexOf(item);  // Find the index of the item
    if (index !== -1) {
        arr.splice(index, 1);  // Remove the item from its current position
        arr.push(item);         // Add the item to the end of the array
    }
    return arr;
}

// Example array
let arr = [1, 2, 3, 4, 5];
let itemToMove = 3;

// Move item to last position
arr = moveToLast(arr, itemToMove);

console.log(arr);  // Output: [1, 2, 4, 5, 3]
Enter fullscreen mode Exit fullscreen mode

Explanation:

  1. arr.indexOf(item): Finds the index of the item in the array.
  2. arr.splice(index, 1): Removes the item at the found index.
  3. arr.push(item): Adds the item to the end of the array.

This method is useful if you have the index of the element and prefer to avoid combining both operations into a single line.


Approach 3: Using filter() and concat()

If you prefer a more functional approach and want to avoid mutating the original array, you can use filter() to remove the item and then concat() to append it to the end.

Code Example:

function moveToLast(arr, item) {
    // Filter out the item and then concatenate it at the end
    return arr.filter(x => x !== item).concat(item);
}

// Example array
let arr = [1, 2, 3, 4, 5];
let itemToMove = 3;

// Move item to last position
arr = moveToLast(arr, itemToMove);

console.log(arr);  // Output: [1, 2, 4, 5, 3]
Enter fullscreen mode Exit fullscreen mode

Explanation:

  1. arr.filter(x => x !== item): Filters out the item from the array.
  2. .concat(item): Adds the item to the end of the filtered array.

This approach creates a new array, so the original array remains unchanged.


Considerations

  • Mutability: The methods using splice() and push() modify the original array. If you need to keep the original array intact, you can use the filter() and concat() approach, which returns a new array.

  • Array Size: The performance of these methods depends on the size of the array. indexOf() and splice() both require a linear scan of the array, so they may not be optimal for large arrays or frequently called operations.

  • Edge Cases:

    • If the item is not in the array, ensure that your code handles that case gracefully (as seen in the indexOf checks).
    • If the item is already at the last position, the array remains unchanged.

Conclusion

Moving an item to the last position in an array is a straightforward operation in JavaScript, and there are multiple ways to achieve this depending on the situation. Using splice() with push() is one of the most efficient and concise methods when you either know the index or the element. Alternatively, using filter() and concat() offers a more functional approach without mutating the original array.

By understanding these methods, you can manipulate arrays efficiently and cater to different use cases in your JavaScript applications.

Top comments (0)