javascript array reorder elements 1

javascript array reorder elements

Array.prototype.move = function (from, to) {
  this.splice(to, 0, this.splice(from, 1)[0]);

Here is what the above code is Doing:
1. We’re creating a new function called move.
2. We’re adding it to the Array prototype.
3. We’re using the splice method to remove an item at index “from” and insert it at index “to”.

Now, we can use the move function like this:

var myArray = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’];
myArray.move(1, 3);
// [‘a’, ‘c’, ‘d’, ‘b’, ‘e’]

Similar Posts