ArticleZip > Move Item In Array To Last Position

Move Item In Array To Last Position

Have you ever needed to rearrange items in an array and move a specific item to the last position? It's a common task in software development, especially when dealing with lists of data. In this guide, we'll walk through a simple and practical way to achieve this in JavaScript.

To move an item in an array to the last position, we can follow these steps:

1. Find the index of the item we want to move. We can use the `indexOf` method to get the index of the item in the array.

2. If the item is found in the array, we need to remove it from its current position. We can use the `splice` method to remove the item at the specific index.

3. Once we have removed the item, we can push it to the end of the array using the `push` method.

Let's put this into action with a practical example. Suppose we have an array of fruits:

Javascript

let fruits = ["apple", "banana", "cherry", "date"];

If we want to move "banana" to the last position in the array, we can do the following:

Javascript

const itemToMove = "banana";

const index = fruits.indexOf(itemToMove);

if (index > -1) {
  fruits.splice(index, 1);
  fruits.push(itemToMove);
}

console.log(fruits); // Output: ["apple", "cherry", "date", "banana"]

In this code snippet, we first find the index of "banana" in the `fruits` array. If the item is found (`index > -1`), we remove it from the array using `splice` and then push it to the end using `push`.

It's important to note that this method modifies the original array. If you want to keep the original array unchanged and create a new array with the item moved to the last position, you can use the following approach:

Javascript

const newArray = [
  ...fruits.filter((fruit) => fruit !== itemToMove),
  itemToMove
];

console.log(newArray); // Output: ["apple", "cherry", "date", "banana"]

By filtering out the item to move and then adding it to the end of the array, we create a new array without altering the original one.

Moving an item in an array to the last position can be a useful technique when working with data manipulation or reordering elements. Whether you're organizing a list of items or implementing specific functionality, this method offers a straightforward way to achieve your desired outcome.

Remember to adapt the code to your specific use case and explore additional array methods for more advanced manipulation tasks. Happy coding!