Change position of element in array using JavaScript code example

change position of element in array using javascript

We can use splice() method to move an element of an array from one position to another in javascript. We will use latest coding principles of JS (ES6). Check the code below –

const changeIndex = (arrayToUpdate, elementToReposition, newIndex) => {
  if(newIndex > arrayToUpdate.length - 1){
    console.log('Array index out of bounds');
    return null;
  } else if (!(arrayToUpdate.includes(elementToReposition))){
    console.log('Element not found');
    return null;

  arrayToUpdate.splice(arrayToUpdate.indexOf(elementToReposition), 1);
  arrayToUpdate.splice(elementToReposition, newIndex);
  return arrayToUpdate;

    Tweet this to help others

Let’s understand the code.

First of all we are using arrow function notation (=>) which is the new standard and widely used in ReactJs.

Our changeIndex() function accepts 3 parameters – arrayToUpdate, elementToReposition, newIndex.

First we are checking if the newIndex value is less than the total length of array. This is because the element can be repositioned only within the current length of array. So, total positions of element are from index 0 to arrayToUpdate.length.

Second we are checking if the elementToReposition lies within array or not. Because if it doesn’t then we can’t move it as it has no position in array previously.

If above both conditions met, then first we are removing the element using splice() function and then adding it back at the required position. This way we can change the position of element in array using changeIndex() function.

You may also like –