skip to Main Content

I’m working on a JavaScript project where I need to move elements within an array from one position to another. I want to move an element at a specific index to a new index, shifting other elements accordingly.
Example:
Suppose I have the following array:

let array = [ 'a', 'b', 'c', 'd', 'e' ];
I

f I want to move the element at index 1 (‘b’) to index 3, the resulting array should be:

// Expected result

[ 'a', 'c', 'd', 'b', 'e' ]

I’ve tried using splice to remove the element and then splice again to insert it at the new position, but I’m not sure if this is the best approach. Here is what I have so far:

function moveElement(array, fromIndex, toIndex) {
    const element = array.splice(fromIndex, 1)[0];
    array.splice(toIndex, 0, element);
    return array;
}

// Example usage:
let arr = [ 'a', 'b', 'c', 'd', 'e' ];
let result = moveElement(arr, 1, 3);
console.log(result); // Output: [ 'a', 'c', 'd', 'b', 'e' ]

Is this a good approach to move elements within an array, or is there a more efficient or idiomatic way to achieve this in JavaScript?
Are there any edge cases or potential pitfalls I should be aware of with this method?
How does this approach perform with large arrays?
Any advice or improvements to the code would be greatly appreciated!

Thank you!

2

Answers


  1. This could be done by a simple swap using JavaScript. Here is how.

    function swap(array, i, j) {
      [array[i], array[j]] = [array[j], array[i]];
    }
    
    Login or Signup to reply.
  2. Have a look at Array.prototype.copyWithin(). Example:

    let a = ['a','b','c','d','e'];
    const from_idx = 1, to_idx = 3, elem = a[from_idx];
    a.copyWithin(from_idx,from_idx+1,to_idx+1)[to_idx]=elem;
    console.log(a);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search