[英]Sort array of object for some keys in javascript
我有一个对象数组。
[{
id: 1,
age: 23
}, {
id: 1,
age: 25
}, {
id: 2,
age: 230
}, {
id: 2,
age: 255
}, {
id: 3,
age: 232
}, {
id: 1,
age: 215
}]
我需要通过对每个 id 的最高年龄进行排序来获得最终数组。 所以最终的数组将是。
[{
id: 1,
age: 215
}, {
id: 2,
age: 255
}, {
id: 3,
age: 232
}]
您可以构建一个哈希,在其中存储每个 id 具有最大年龄的对象。 然后按数字对其键进行排序并按该顺序获取值。
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];
});
这里只有一个班轮
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>");
您通常会使用filter
和indexOf
从数组中删除重复元素。 在数组元素是对象的情况下,您可以使用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);
此外,您需要注意其浏览器支持。
或者通过这种方式避免使用 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;
}
您可以使用 vanillaJS 以这种方式进行排序。
function sortByAgeDesc(a,b) {return a.age > b.age ? -1 : a.age === b.age ? 0 : 1;}
output = input.sort(sortByAgeDesc);
现在的问题是你只想要不同的 id。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.