JavaScript

Change the position of an element in an array with JavaScript

November 7, 2021

Change the position of an element in an array with JavaScript

In this article we’ll look at a way to change the position of an element in the array, applying native JavaScript functions, in an easy way.

Change the position of an element in an array cover

What’s up programmer, okay? Let’s learn something new!

Watch this content on YouTube:

We can do the manipulation of an array via JavaScript, to position the elements at an index we want

This is useful, for example, to display the items in a select, and update event, to check the options with values that come in an array

So we can manipulate the items first and then insert them in the options.  

Let’s put it into practice?

Changing the position of an element in the array: practical

We can create a function to solve this problem, check it out:

function changePosition(arr, from, to) {
 arr.splice(to, 0, arr.splice(from, 1)[0]);
 return arr;
};

let arr = [1,2,4,5,6,7,8,9,10,3];

arr = changePosition(arr, 9, 3);

console.log(arr); // [1,2,3,4,5,6,7,8,9,10]

We create a function called changePosition, which takes three arguments: the array that we’re going to change the elements to, the position the element is in (from) and the position the element should be in (to)

Note that we can organize the order of the array, changing the number 3 from the last position to the number 2 (arrays start counting from 0)

It’s now easy for you to change the position of an element in the array, right?

Hint: how to change the element from the first position to the last in the array

And there’s also a bonus tip in this article, let’s change the position of the first element to the last one in the array.

See how simple it is:

let arr = [3,1,2];

arr.push(arr.splice(0,1)[0]);

console.log(arr); // [ 1, 2, 3 ]

We simply remove the first element from the array with splice, and get it on the return with the [0]

Then we push the array, which adds an element to the end of the array.

And this element will be the first one, which was removed with splice

Conclusion

In this article we learned a way of changing the position of an element in an array

We created a function so that our code can be reused and be well structured in our project helpers 

And yet, a super tip on how to put the first element as last one in the array

Want to learn more about JavaScript? Click here!

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x