Different ways of swapping elements in a JS Array
I was working on a UI where a group of cards are getting rendered based on the data that is present in the array & I've got a scenario where I have to swap my cards to match UI ( first card needs to be placed with 3rd card and vice versa). This is where I got pushed into a situation to swap elements in an array which contains the information to render the cards.
So at first I used a simple way of swapping elements in array by taking a temporary variable and assigned first element's value to it and then I set the value of third element to the first element. As a last step I assigned value of temporary variable to the third element. (PFB, code snippet)
And then I realised that there is far better approach compare to the above approach and that can be coded in single line. And that approach is array destructuring. I just created a new array containing both elements in a particular order, then assign it to a new array that contains both elements in the reversed order.
After trying the above approach I realised how could I forgot to use splice method to achieve the same result. BTW, splice method can be used to remove one or more element(s) from an array and replace the element(s) with any specified element. Below snippet explains the syntax of splice method.
领英推荐
splice method returns array of the deleted elements from the given array.
So, we can use this splice method for swapping of elements too.
In this article I tried to show 3 ways of swapping elements in an array but I personally like the 2nd method(array destructuring way).
Thanks for reading!!
HIRING NOW!! React/Angular/Node UI/Full-Stack Developer (1-3/3-5/5-7 yrs)
2 年Nice, Thank You for putting it together