Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript change place of array element

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")
like image 443
Irakli Avatar asked Sep 10 '12 19:09

Irakli


4 Answers

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;
like image 68
Johnny Mopp Avatar answered Oct 11 '22 18:10

Johnny Mopp


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/

like image 27
jbabey Avatar answered Oct 11 '22 18:10

jbabey


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;
    }
};
like image 2
Tal Shahar Avatar answered Oct 11 '22 17:10

Tal Shahar


arr = [0,1,2,3];
a = arr[3];
arr[3] = arr[0];
arr[0] = a;
like image 1
picmate 涅 Avatar answered Oct 11 '22 18:10

picmate 涅