Borja
Borja

Reputation: 3559

How can i sort 3 dimensional array in javascript?

i have this 3D array

var array = [
     [
       {
          ipo: 10
       }
     ],
     [
       {
          ipo: 5
       }
     ],
     [
       {
          ipo: 15
       }
     ],
];

i want to sort by ascending and by descending. I tried this:

array.sort(function(a, b) {   //ascending
 return a.ipo - b.ipo;
}); 

but doesn't works... What do you suggest ? maybe i need to add for loop inside function?

Upvotes: 2

Views: 1402

Answers (2)

Aniket Sahrawat
Aniket Sahrawat

Reputation: 12937

It does not work because there is an b.ipo does not exist. You can use b[0].ipo then compare it, eg:

var array = [ [ { ipo: 10 } ], [ { ipo: 5 } ], [ { ipo: 15 } ], ];
array.sort(function(a, b) {
 return a[0].ipo > b[0].ipo;
}); 
console.log(array);

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386680

Assuming only one element in the inner arrays, you could take this element for accessing the property

var array = [[{ ipo: 10 }], [{ ipo: 5 }], [{ ipo: 15 }]];

array.sort(function(a, b) {
    return a[0].ipo - b[0].ipo;
});

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 7

Related Questions