Home > Web Front-end > JS Tutorial > How Can I Efficiently Move an Element Within a JavaScript Array?

How Can I Efficiently Move an Element Within a JavaScript Array?

Mary-Kate Olsen
Release: 2024-11-25 22:07:11
Original
194 people have browsed it

How Can I Efficiently Move an Element Within a JavaScript Array?

Moving Elements Within an Array

In programming, it's often necessary to manipulate arrays by changing the positions of their elements. One common operation is moving an element from one array position to another.

The Challenge

Consider the following array:

var array = [ 'a', 'b', 'c', 'd', 'e'];
Copy after login

The task is to write a function that allows you to move any element of the array to a specified index. For example, you may want to move 'd' to the left of 'b' or 'a' to the right of 'c'.

The Solution

Below is a JavaScript function that tackles this challenge:

function array_move(arr, old_index, new_index) {
    if (new_index >= arr.length) {
        var k = new_index - arr.length + 1;
        while (k--) {
            arr.push(undefined);
        }
    }
    arr.splice(new_index, 0, arr.splice(old_index, 1)[0]);
}
Copy after login

Usage

To move an element, simply call the array_move function with the following arguments:

  • arr: The array you want to modify.
  • old_index: The current index of the element you want to move.
  • new_index: The desired index for the element after it has been moved.

For example, to move 'd' to the left of 'b', you would call:

array_move(array, 3, 1);
Copy after login

This would result in the following array:

['a', 'd', 'b', 'c', 'e']
Copy after login

The above is the detailed content of How Can I Efficiently Move an Element Within a JavaScript Array?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template