I have nested array in javascript like this:
testArray['element1'] = {par1: "value1", par2: "value2" ... }
testArray['element2'] = {par1: "value1", par2: "value2" ... }
testArray['element3'] = {par1: "value1", par2: "value2" ... }
testArray['element4'] = {par1: "value1", par2: "value2" ... }
so how can I change place of element? for example instead of
("element1", "element2", "element3","element4")
to be
("element4", "element2", "element3","element1")
or
("element1", "element4", "element3","element2")
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;
}
};
arr = [0,1,2,3];
a = arr[3];
arr[3] = arr[0];
arr[0] = a;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With