简体   繁体   中英

Sort array of object for some keys in javascript

I have one array of object like.

[{
  id: 1,
  age: 23
}, {
  id: 1,
  age: 25
}, {
  id: 2,
  age: 230
}, {
  id: 2,
  age: 255
}, {
  id: 3,
  age: 232
}, {
  id: 1,
  age: 215
}]

I need to get the final array by sorting with hightest age for each id. so final array will be.

[{
    id: 1,
    age: 215
  }, {
    id: 2,
    age: 255
  }, {
    id: 3,
    age: 232
  }]

You can build a hash in which you store the object with the maximum age for each id. Then sort its keys numerically and get the values in that order.

var hash = array.reduce(function(hash, obj) {
  if(!hash[obj.id]) hash[obj.id] = obj;
  else if(hash[obj.id].age < obj.age) hash[obj.id] = obj;
  return hash;
}, Object.create(null));
Object.keys(hash).sort(function(a,b) {
  return a - b;
}).map(function(id) {
  return hash[id];
});

a single liner here

 var arr = [{ id: 1, age: 23, }, { id: 1, age: 25, }, { id: 2, age: 230, }, { id: 2, age: 255, }, { id: 3, age: 232, }, { id: 1, age: 215, }], lut = {}, res = arr.sort((a,b) => b.age - a.age).filter(o => lut[o.id] ? false : lut[o.id] = true).sort((a,b) => a.id - b.id); document.write("<pre>" + JSON.stringify(res,null,2) + "</pre>");

You would normally use filter with indexOf to remove duplicate elements from an array . In the case when array elements are objects, you can use findIndex to search for the index of a element by some given property values.

 let result = [{ id: 1, age: 23, }, { id: 1, age: 25, }, { id: 2, age: 230, }, { id: 2, age: 255, }, { id: 3, age: 232, }, { id: 1, age: 215, }].sort((a,b) => b.age - a.age) .filter((row,pos,self) => self.findIndex(item => item.id === row.id) === pos) .sort((a,b) => a.id - b.id); document.body.textContent = JSON.stringify(result);

Also, you need to pay attention to its browser support.

or this way to avoid using lodash's uniq() method:

arr.sort(function(a,b){
  return b.id > a.id;
}).reverse();
var max = arr.length;
var i = 0;
while(i < max - 1){
  if (arr[i].id === arr[i+1].id) arr.splice(i+1,1);
  else i++
  max = arr.length;
}

You can do sorting this way Using vanillaJS.

function sortByAgeDesc(a,b) {return a.age > b.age ? -1 : a.age === b.age ? 0 : 1;}


output = input.sort(sortByAgeDesc);

Now the question is you want only distinct ids.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM