Languages
[Edit]
EN

JavaScript - move array element from one position to another

0 points
Created by:
ArcadeParade
666

In this article, we would like to show you how to move an array element from one position to another in JavaScript.

Practical examples

Example 1

In this example, we create a reusable arrow function that uses splice() method to move array element from indexOld position to indexNew.

Note: When indexNew is greater or equal to array.length the remaining space will be filled with undefined values (go to the Example 2).

// ONLINE-RUNNER:browser;

const moveElement = (array, indexOld, indexNew) => {
    if (indexNew >= array.length) {
        let n = indexNew - array.length + 1;
        while (n--) {
            array.push(undefined);
        }
    }
    array.splice(indexNew, 0, array.splice(indexOld, 1)[0]);
};


// Usage example:

const array = ['a', 'b', 'c'];

moveElement(array, 0, 1); // moves element from index 0 to index 1

console.log(array); // [ 'b', 'a', 'c' ]

Example 2

In this section, we present how the moveElement() method works when indexNew is greater than array.length value.

// ONLINE-RUNNER:browser;

const moveElement = (array, indexOld, indexNew) => {
    if (indexNew >= array.length) {
        let n = indexNew - array.length + 1;
        while (n--) {
            array.push(undefined);
        }
    }
    array.splice(indexNew, 0, array.splice(indexOld, 1)[0]);
};


// Usage example:

const array = ['a', 'b', 'c'];

moveElement(array, 0, 5); // moves element from index 0 to index 5

console.log(array); // ['b','c', , , ,'a']

 

References

  1. Array.prototype.splice() - JavaScript | MDN

Alternative titles

  1. JavaScript - move array element from one index to another
  2. JavaScript - move array item from one index to another
  3. JavaScript - change index of array item
  4. JavaScript - change index of array element
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join