如何从特定阵列中获取新阵列?
我不知道如何处理这样的数组:
let arr1 = [
{name: 'a', age: 1},
{name: 'a', age: 2},
{name: 'a', age: 3},
{name: 'b', age: 1},
{name: 'b', age: 2}
{name: 'b', age: 3}
{name: 'c', age: 1}
{name: 'c', age: 2}
...
]
“我想要这个结果:从具有相同name
的每个项目中,选择最大的age
值”
let arr2 = [
{name: 'a', age: 3},
{name: 'b', age: 3},
{name: 'c', age: 2}
...
]
答案 0 :(得分:3)
只需使用filter
为其age
选择具有最高name
的所有项目。
let arr1 = [{name:'a',age:1},{name:'a',age:2},{name:'a',age:3},{name:'b',age:1},{name:'b',age:2},{name:'b',age:3}];
const biggest = arr1.reduce((a, { name, age }) => {
a[name] = a[name] || age;
age > a[name] ? a[name] = age : a[name];
return a;
}, {});
let arr2 = arr1.filter(({ name, age }) => biggest[name] == age);
console.log(arr2);
.as-console-wrapper { max-height: 100% !important; top: auto; }
答案 1 :(得分:2)
您可以结合使用reduce
和Object.values
const arr1 = [
{name: 'a', age: 1},
{name: 'a', age: 2},
{name: 'a', age: 3},
{name: 'b', age: 1},
{name: 'b', age: 2},
{name: 'b', age: 3},
{name: 'c', age: 1},
{name: 'c', age: 2},
]
const maxNames = arr1.reduce((maxNamesObject, item) => {
const { name, age } = item
const maxItem = maxNamesObject[name]
if (!maxItem || age > maxItem.age) {
maxNamesObject[name] = item
}
return maxNamesObject
}, {})
const output = Object.values(maxNames)
console.log(output)
答案 2 :(得分:0)
从此答案中提取:How to filter object array based on attributes?
您可以使用Array.prototype.filter
方法:
let arr2 = arr1.filter(function (obj) {
return obj.age === 3;
});
答案 3 :(得分:0)
这是一个更漂亮的解决方案:
let arr1 = [
{name: 'a', age: 1},
{name: 'a', age: 2},
{name: 'a', age: 3},
{name: 'b', age: 1},
{name: 'b', age: 2},
{name: 'b', age: 3},
{name: 'c', age: 1},
{name: 'c', age: 2},
]
arr2 = Array.from(new Set(arr1.map(e => e.name))).map(e => {
return {
name: e,
age: Math.max(...arr1.filter(ee => ee.name == e).map(ee => ee.age))
}
})
console.log(arr2)
Blockquote
答案 4 :(得分:0)
我的解决方案:
const arr1 = [
{name: 'a', age: 1},
{name: 'a', age: 2},
{name: 'a', age: 3},
{name: 'b', age: 1},
{name: 'b', age: 2},
{name: 'b', age: 3},
{name: 'c', age: 1},
{name: 'c', age: 2},
]
let arr2 = arr1.reduce((acc, item) => {
let objectExists = acc.find(e => e.name === item.name)
if (!objectExists) acc.push(item)
else if (objectExists.age < item.age) {
acc[acc.indexOf(objectExists)].age = item.age
}
return acc
}, [])
console.log(arr2)
答案 5 :(得分:-1)
我没有注意到您更新了问题。这不是最专业的代码。
let arr1 = [
{name: 'a', age: 1}, {name: 'a', age: 2}, {name: 'a', age: 3},
{name: 'b', age: 1}, {name: 'b', age: 2}, {name: 'b', age: 3},
{name: 'c', age: 1}, {name: 'c', age: 2} ];
let names = [];
let output = [];
for(obj of arr1){
if (!names.includes(obj.name)) names.push(obj.name);
}
for(obj of names){
let current = arr1.filter(x => x.name === obj)
.reduce((a,b) => a.age > b.age ? a : b);
output.push(current);
}
console.log(output);