Swap two items, elements or objects in an array with Javascript

Sometimes you want to rearrange the position of two products or something so that the order displays in turn. And this brief article will help you do that very easily.

Swap two items in an array with Javascript?


var list = ["a", "b", "c", "d", "e", "f", "g"];

function swap(x, y){
	var z = list[y];
    list[y] = list[x];
    list[x] = z;
}

swap(2, 5);

console.log(list); // a b f d e c g

Create swap prototype

Array.prototype.swap = function (x, y) {
  var z = this[x];
  this[x] = this[y];
  this[y] = z;
  return this;
}
// Then use:
list.swap(0, 1);

It is easy, right? Let’s share!

#javascript

Swap two items, elements or objects in an array with Javascript
128.85 GEEK