Move elements in array javascript

Move elements in array javascript

Last updated: Dec 22, 2022
Reading time · 4 min

banner

# Move an Array element from one Index to another in JS

To change the position of an element in an array:

  1. Use the splice() method to remove the element at the specified index from the array.
  2. Use the splice() method to insert the element at the new index in the array.
Copied!
const arr = ['css', 'js', 'ts']; const fromIndex = arr.indexOf('css'); // 👉️ 0 const toIndex = 2; const element = arr.splice(fromIndex, 1)[0]; console.log(element); // ['css'] arr.splice(toIndex, 0, element); console.log(arr); // 👉️ ['js', 'ts', 'css']

We changed the position of the array element with value css from index 0 to index 2 .

We first used the Array.indexOf method to get the index of the element.

Copied!
const arr = ['css', 'js', 'ts']; console.log(arr.indexOf('css')); // 👉️ 0

We then used the Array.splice method, passing it the following 2 arguments:

  1. start index — the index at which to start changing the array.
  2. delete count — how many elements should be deleted from the array.

The splice() method returns an array containing the removed elements.

Copied!
const arr = ['css', 'js', 'ts']; const splice = arr.splice(0, 1); console.log(splice) // 👉️ ['css']

We know that we only deleted 1 element from the array, so we directly access the array element at index 0 to get the value of the element we will insert at the new position.

The last step is to call the splice() method again. However, this time we use it to add an element to the array at a specific index.

The 3rd argument we passed to the splice method is the element to add to the array.

Copied!
const arr = ['css', 'js', 'ts']; const fromIndex = arr.indexOf('css'); // 👉️ 0 const toIndex = 2; const element = arr.splice(fromIndex, 1)[0]; console.log(element); // ['css'] arr.splice(toIndex, 0, element); console.log(arr); // 👉️ ['js', 'ts', 'css']

We set the start index argument to the new position the element should be placed in.

Lastly, we set the delete count argument to 0 to denote that we don’t want to remove any elements from the array.

We used the splice method to:

  1. Remove an element at a specific index from an array and get its value.
  2. Add an element to an array at a specific index.
Читайте также:  Convert bytearray to string python

I would have liked to have 2 separate built-in methods to achieve these 2 very different goals. However, this is the way to do it in JavaScript.

You can also shorten the code to a single line, but it becomes less readable.

Copied!
const arr = ['css', 'js', 'ts']; const fromIndex = arr.indexOf('css'); // 👉️ 0 const toIndex = 2; arr.splice(toIndex, 0, arr.splice(fromIndex, 1)[0]); console.log(arr); // 👉️ ['js', 'ts', 'css']

# Creating a reusable function that moves an element

You can also create a reusable function that takes the array, the fromIndex and toIndex arguments and moves the element.

Copied!
function moveElement(array, fromIndex, toIndex) const element = array.splice(fromIndex, 1)[0]; console.log(element); arr.splice(toIndex, 0, element); return arr; > const arr = ['css', 'js', 'ts']; const fromIndex = arr.indexOf('css'); // 👉️ 0 const toIndex = 2; const result = moveElement(arr, fromIndex, toIndex); console.log(result); // 👉️ [ 'js', 'ts', 'css' ]

The function moves the array element in place and returns the array.

If you want to create a new array without changing the original, create a shallow copy.

Copied!
function moveElement(array, fromIndex, toIndex) const arrayCopy = [. array]; const element = arrayCopy.splice(fromIndex, 1)[0]; console.log(element); arrayCopy.splice(toIndex, 0, element); return arrayCopy; > const arr = ['css', 'js', 'ts']; const fromIndex = arr.indexOf('css'); // 👉️ 0 const toIndex = 2; const result = moveElement(arr, fromIndex, toIndex); console.log(result); // 👉️ [ 'js', 'ts', 'css' ] console.log(arr); // 👉️ [ 'css', 'js', 'ts' ]

We used the spread syntax (. ) to create a shallow copy of the array and called the splice() method on the copy.

The moveElement() function doesn’t change the original array, it returns a new array that reflects the changes.

Alternatively, you can use the array-move npm package.

# Change the Position of an Element in an Array using array-move

This is a two-step process:

  1. Open your terminal in your project’s root directory (where your package.json file is) and install the array-move package.
Copied!
# 👇️ with npm npm install array-move # 👇️ with yarn yarn add array-move
Copied!
import arrayMoveImmutable> from 'array-move'; const arr = ['css', 'js', 'ts']; const fromIndex = arr.indexOf('css'); // 👉️ 0 const toIndex = 2; const newArray = arrayMoveImmutable(arr, fromIndex, toIndex); console.log(newArray); // 👉️ [ 'js', 'ts', 'css' ] console.log(arr); // 👉️ [ 'css', 'js', 'ts' ]

The arrayMoveImmutable function takes the array, the from index and the to index as arguments and returns a new array with the specified element moved.

The function doesn’t mutate the original array in place.

If you want to change the original array in place, use the arrayMoveMutable() function.

Copied!
import arrayMoveMutable> from 'array-move'; const arr = ['css', 'js', 'ts']; const fromIndex = arr.indexOf('css'); // 👉️ 0 const toIndex = 2; arrayMoveMutable(arr, fromIndex, toIndex); console.log(arr); // 👉️ [ 'js', 'ts', 'css' ]

The arrayMoveMutable() function takes the array, the from index and the to index as arguments, changes the array in place and returns undefined .

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Moving Element In An Array From Index To Another

I was working on a project when I faced an unprecedented and obvious issue. How do I suppose to move an element in an array form one position to another? My goal is to move an element in index-0 to index-2. Something like this:

const input = ["a", "b", "c"]; const expected = ["b", "c", "a"]; 

The simplest way, using splice() which gives me the ability to add and remove elements in an array. First, let’s delete element in index-0:

function move(input, from)  const numberOfDeletedElm = 1; // delete one element only, in index-from const arrDeletedElem = input.splice(from, numberOfDeletedElm); // ["a"]=["a", "b", "c"].splice(0, 1); // and input array is ["b", "c"] > 
const elm = input.splice(from, numberOfDeletedElm)[0]; 
const numberOfDeletedElm = 0; input.splice(2, numberOfDeletedElm, elm); 
function move(input, from, to)  let numberOfDeletedElm = 1; const elm = input.splice(from, numberOfDeletedElm)[0]; numberOfDeletedElm = 0; input.splice(to, numberOfDeletedElm, elm); > // move(["a", "b", "c"], 0, 2) >> ["b", "c", "a"] 

Of course, this can go deeper, that’s why I created move-position. Which contains utility functions for moving index in an array. Since releasing V1, move-position can deal with the following cases: 1- Moving one element form/to index using: move .

const input = ["a", "b", "c"]; // move element form index=0, to index=2 const result = move(input, 0, 2); // ["b", "c", "a"]; 
const input1 = ["a1", "b1", "c1"]; const input2 = ["a2", "b2", "c2"]; const inputs = [input1, input2]; const result = moveMultiArr(inputs, 2, 0); // result[0] > ["c1", "a1", "b1"]; // result[1] > ["c2", "a2", "b2"]; 
const input = ["a", "b", "c"]; const movingMap = [  from: 0, to: 2 >,  from: 2, to: 1 > ]; const result = moveMultiIndex(input, movingMap); // result > [ 'a', 'c', 'a' ] 

Источник

How to Move an Array Element from One Array Position to Another

In this tutorial, you will find an insert strategy of moving an array element to another position.

Handling the issue is possible with the array-move method which returns a new array with the item moved to the new position:

w3docs logo

Javascript returns a new array with the item moved to the new position

function arrMove(arr, oldIndex, newIndex) < if (newIndex >= arr.length) < let i = newIndex - arr.length + 1; while (i--) < arr.push(undefined); >> arr.splice(newIndex, 0, arr.splice(oldIndex, 1)[0]); return arr; >; // returns [22, 11, 33] console.log(arrMove([11, 22, 33], 0, 1));

The last return is for testing purposes. The splice() method performs operations on the array in-place, so a return is not necessary. If you want to avoid it and return a copy, you can use the slice() method.

If newIndex is greater than the array length, you should pad the array with new undefined. It will push undefined on the array until you have the proper length.

Then you should splice out the old item. The splice() method returns the item that was spliced out in an array. Since in the given example, this was [1], you should take the first index of that array to get the raw 1.

Then you should use splice() to insert this item in the newIndex’s place. As you have already padded the array, it will appear in the right place.

For negative indexes use the following code piece:

w3docs logo

Javascript new array splice item to the new position

function arrayMove(arr, oldIndex, newIndex) < while (oldIndex < 0) < oldIndex += arr.length; >while (newIndex < 0) < newIndex += arr.length; >if (newIndex >= arr.length) < let i = newIndex - arr.length + 1; while (i--) < arr.push(undefined); >> arr.splice(newIndex, 0, arr.splice(oldIndex, 1)[0]); return arr; >; // returns [11, 33, 22] console.log(arrayMove([11, 22, 33], -1, -2));

The splice() Method

The Array.prototype.splice() method changes the content of an array by removing or replacing existing items or adding new items in place. Unlike the slice() method, slice() changes the original array.

The slice() Method

The Array.prototype.slice() method returns a new array copying to it all the items from index start to the end (but the end is not included) where start and end represent the index of items in that array. The original array remains unchanged.

BookDuck

  • How to Check if an Element is Present in an Array in JavaScript?
  • How to Remove Empty Elements from an Array in Javascript
  • How to Remove an Element from an Array in JavaScript
  • How to Insert an Item into an Array at a Specific Index
  • How To Add New Elements To A JavaScript Array
  • How to Append an Item to an Array in JavaScript
  • How to Randomize (shuffle) a JavaScript Array
  • How to Loop through an Array in JavaScript
  • How to Copy Array Items into Another Array
  • How to Get the Last Item in an Array
  • How to Sort an Array of Integers
  • JavaScript Data Types
  • JavaScript Array methods
  • JavaScript Arrays

Источник

Оцените статью