我有一个对象数组。使用循环后的reduce方法我想接收两个单独的数组。现在,我正在这样做。
const dogs = [
{ weight: 22, curFood: 250, owners: ['Alice', 'Bob'] },
{ weight: 8, curFood: 200, owners: ['Matilda'] },
{ weight: 13, curFood: 275, owners: ['Sarah', 'John'] },
{ weight: 32, curFood: 340, owners: ['Michael'] },
];
所以,通过下面的reduce方法,我收到了我想要的结果(2个数组)。
const ownersEatTooMuch = dogs.reduce(function (acc, dog) {
if (dog.curFood > dog.recommended * 1.1) {
acc.push(dog.owners);
}
return acc.flat();
}, []);
const ownersEatTooLess = dogs.reduce(function (acc, dog) {
if (dog.curFood < dog.recommended * 0.9) {
acc.push(dog.owners);
}
return acc.flat();
}, []);
但是是否可以将其合并到一个reduce方法中以创建2个数组。我想象这样的情况,
const [ownersEatTooMuch1, ownersEatTooLess1] = dogs.reduce(function (dog) {
// When the condition will be true i want to fill first array ownersEatTooMuch1 and when another condition will be true i want to fill second array ownersEatTooLess1
}, [[], []]);
const [ownersEatTooMuch1, ownersEatTooLess1] = dogs.reduce(
function (dog) {
if (dog.curFood > dog.recommended * 1.1) {
acc.push(dog.owners);
}
},
[[], []]
);
我只是不明白如何确定这些之间的[[],[],然后推入ownerEatTooMuch1或此处ownerEatTooLess1
我希望这就是您正在寻找的。 因为您的示例代码不起作用(
recommended
未定义),并且输出不清楚,所以我不确定这是否是您想要的。
根据您提供的代码,您想要 2 个“吃太多”或“吃太少”的数组。
那些既不“太多”也不“太少”的情况呢? 请参阅我在数组定义中的评论:
does not apppear anywhere, neither "too much" or "too less"
const dogs = [
{ weight: 22, curFood: 250, owners: ['Alice', 'Bob'], recommended: 10 },
{ weight: 8, curFood: 200, owners: ['Matilda'], recommended: 2000 },
{ weight: 13, curFood: 275, owners: ['Sarah', 'John'], recommended: 300 }, // does not apppear anywhere, neither "too much" or "too less"
{ weight: 32, curFood: 340, owners: ['Michael'], recommended: 1000 },
];
const [ownersEatTooMuch, ownersEatTooLess] = dogs.reduce((arr, dog) => {
if (dog.curFood > dog.recommended * 1.1) {
arr[1].push(...dog.owners);
}
if (dog.curFood < dog.recommended * 0.9) {
arr[0].push(...dog.owners);
}
return arr;
}, [
[], // too much
[] // too less
]);
console.log(ownersEatTooLess, ownersEatTooMuch)
reduce 迭代每次传递给它的初始数组都会返回,这是一个 2 层数组。
然后根据您的计算填充这些数组。
reduce 返回的 2 层数组随后被解构为变量
ownersEatTooMuch
& ownersEatTooLess
。