需要减少对象数组以返回同名的最高值。
需要以下内容,
[
{
name: 'a',
value: 20
},
{
name: 'a',
value: 80
},
{
name: 'b',
value: 90
},
{
name: 'b',
value: 50
}
]
返回
[
{
name: 'a',
value: 80
},
{
name: 'b',
value: 90
}
]
我有一个解决方案,但似乎有点太多,想知道是否有更直接的方法来实现它?
以下是我能想到的解决方案:
var toReduce = [
{
'name': 'a',
'value': 20
},
{
'name': 'a',
'value': 80
},
{
'name': 'b',
'value': 90
},
{
'name': 'b',
'value': 50
}
];
function arrayReducer(arrayToReduce) {
// Created an object separating by name
let reduced = arrayToReduce.reduce((accumulator, currentValue) => {
(accumulator[currentValue.name] =
accumulator[currentValue.name] || []).push(currentValue);
return accumulator;
}, {});
// Reduce object to the highest value
for (let quotes of Object.keys(reduced)) {
reduced[quotes] = reduced[quotes].reduce(
(accumulator, currentValue) => {
return accumulator && accumulator.value > currentValue.value
? accumulator
: currentValue;
}
);
}
// return only object values
return Object.values(reduced);
}
console.log(arrayReducer(toReduce));
您可以在
reduce()
期间计算最大值,而不是在单独的循环中计算。
var toReduce = [{
'name': 'a',
'value': 20
},
{
'name': 'a',
'value': 80
},
{
'name': 'b',
'value': 90
},
{
'name': 'b',
'value': 50
}
];
function arrayReducer(arrayToReduce) {
// Created an object separating by name
let reduced = arrayToReduce.reduce((accumulator, currentValue) => {
accumulator[currentValue.name] = {
name: currentValue.name,
value: accumulator.hasOwnProperty(currentValue.name) ? Math.max(accumulator[currentValue.name].value, currentValue.value) : currentValue.value
};
return accumulator;
}, {});
// return only object values
return Object.values(reduced);
}
console.log(arrayReducer(toReduce));