有什么方法可以使用reduce函数返回多个对象吗?例如,我想回到最年长的年龄,我有3个年龄相同的人。见下文,谢谢!
var dataArray = [
{name: "Roy", age: 24, sex: "M"},
{name: "Ben", age: 25, sex: "M"},
{name: "Jamie", age: 23, sex: "F"},
{name: "David", age: 25, sex: "M"},
{name: "Bob", age: 25, sex: "M"}
];
var oldestPeople = dataArray.reduce(function(max, cur) {
console.log("Max is " + max["name"]);
console.log("Cur is " + cur["name"]);
if (cur["age"] === max["age"]) {
return [max, cur];
} else if (cur["age"] > max["age"]) {
return cur;
} else {
return max;
}
});
我能够让它返回两个对象,但是一旦返回[max,cur],我的max将变为undefined。再次感谢!
答案 0 :(得分:1)
查看文档https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
然后第一次回调它是前一次调用回调的返回值。
所以你遇到的问题是,有时你返回并且数组[max,cut]和其他时候你返回一个值cur或max - 只是坚持总是返回一个数组,你应该没问题,比如
if (max)
console.log("Max is " + max[0]["name"]);
else
return [cur];
console.log("Cur is " + cur["name"]);
if (cur["age"] === max[0]["age"]) {
return max.concat([cur]);
} else if (cur["age"] > max[0]["age"]) {
return [cur].concat(max);
} else {
return max.concat([cur]);
}
答案 1 :(得分:0)
如果您想使用reduce
,可以使用类似
var oldestPeople = dataArray.reduce(function(max, cur) {
if (cur.age === max.age) {
max.people.push(cur);
} else if (cur.age > max.age) {
max.age = cur.age;
max.people = [cur];
}
return max;
}, {age: -Infinity, people: []}).people;
但也许我更喜欢forEach
:
var maxAge = -Infinity,
oldestPeople = [];
dataArray.forEach(function(cur) {
if (cur.age === maxAge) {
oldestPeople.push(cur);
} else if (cur.age > maxAge) {
maxAge = cur.age;
oldestPeople = [cur];
}
});