0

Here is my array of objects:

var arr = [
    {name:"Mike", age:17},
    {name:"John", age:21},
    {name:"Sam", age:32},
    {name:"Mark", age:23}
]

For instance I have hundredth of thousands of objects in this array.

What is the fastest way to filter it by age (greatest to least)?

Here is my expected output:

var arr = [
    {name:"Sam", age:32},
    {name:"Mark", age:23}
    {name:"John", age:21},
    {name:"Mike", age:17},      
]
Michael
  • 15,386
  • 36
  • 94
  • 143

1 Answers1

1

I think that you need is sorting. So you could try something like this:

// for sorting them from the greatest to the lower
function compare(a,b) {
   return b.age-a.age;
}

arr.sort(compare);

If you want to sort them from the lower to the greatest, you have to use the following compare

function compare(a,b) {
   return a.age-b.age;
}

Please have a look here JSFiddle.

Christos
  • 53,228
  • 8
  • 76
  • 108