by eidam

Changing the position of an element in an array with javascript

For example, I want to move element ‘a’ in array [‘a’, ‘b’, ‘c’, ‘d’] two position after its actual position to have something like [‘b’, ‘c’, ‘a’, ‘d’]

Here is the solution:


It consists from 3 main parts:


1. Getting old index

Actually, this is done by the simple indexOf() method (that could be replaced by iteration over the array).


2. Getting new index

Firstly we sum up the oldIndex and positionChanged values by inserting them into parentheses to avoid a string conversion. Than we have to check, if this number isn’t smaller than 0 or bigger than length of array.


3. Moving element

Here we clone our array to arrayClone variable by using slice() method. As I noticed, this is the best way for cloning arrays (see jsperf).

Then we splice the array two times. Splice method is a kind of universal tool here, because it can both remove elements and insert them (see splice method on mozilla). So, first time we removed element with arrayClone.splice(oldIndex,1) . Then by adding the third argument, we put element again in the new position by arrayClone.splice(oldIndex,1).


And here is the codepen implementation:

See the Pen Moving array elements by Eidam (@eidam61) on CodePen.