Javascript change place of array element Javascript change place of array element arrays arrays

Javascript change place of array element


First, build the object properly:

array = {  'element1' : {par1: 'value1', par2: 'value2', par3: 'value3'....},  'element2' : {par1: 'value1', par2: 'value2', par3: 'value3'....},  'element3' : {par1: 'value1', par2: 'value2', par3: 'value3'....},  'element4' : {par1: 'value1', par2: 'value2', par3: 'value3'....}}

Then swap:

var tmp = array['element2'];array['element2'] = array['element1'];array['element1'] = tmp;


What you've posted in your question is not an array, it's not even valid javascript syntax. Since you ask about order, I'll assume you are not using objects as objects in javascript have no guaranteed order.

That being said, I'm going to assume you have an array declared as such:

var testArray = [{ ... }, { ... }, { ... }];

To swap two elements, you just need a generic swap function:

var swap = function(theArray, indexA, indexB) {    var temp = theArray[indexA];    theArray[indexA] = theArray[indexB];    theArray[indexB] = temp;};swap(testArray, 0, 1);

http://jsfiddle.net/jbabey/gRVn5/


you can add it as an array prototype like so:

Array.prototype.swap = function (index1, index2) {    if (index1 <= this.length && index2 <= this.length) {        var temp = this[index2];        this[index2] = this[index1];        this[index1] = temp;    }};