2

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?

1
  • 1
    do you have more elements in the inner arrays? btw, it's only 2D. Commented Feb 13, 2018 at 12:26

2 Answers 2

7

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; }

Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.