-4

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
  }]
Devank
  • 159
  • 2
  • 9
Rahul Tailwal
  • 3,183
  • 3
  • 14
  • 27

5 Answers5

1

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];
});
Oriol
  • 274,082
  • 63
  • 437
  • 513
0

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>");
Redu
  • 25,060
  • 6
  • 56
  • 76
0

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.

Community
  • 1
  • 1
Lewis
  • 14,132
  • 12
  • 66
  • 87
0

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;
}
kevin ternet
  • 4,514
  • 2
  • 19
  • 27
0

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.

Devank
  • 159
  • 2
  • 9