简体   繁体   English

对javascript中的某些键的对象数组进行排序

[英]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.我需要通过对每个 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.您可以构建一个哈希,在其中存储每个 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 .您通常会使用filterindexOf 从数组中删除重复元素 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.在数组元素是对象的情况下,您可以使用findIndex通过某些给定的属性值搜索元素的索引。

 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:或者通过这种方式避免使用 lodash 的 uniq() 方法:

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.您可以使用 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.现在的问题是你只想要不同的 id。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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