例如,这是一个示例数组:
const fruits = [
{name:"orange", qty: 1},
{name:"orange", qty: 2},
{name:"banana", qty: 4},
{name:"apple", qty: 6},
{name:"kiwi", qty: 3},
{name:"apple", qty: 2}
];
我需要做的是将所有对象与名称apple
分组在一个数组中,其余的分组到另一个数组中。预期:
const fruits1 = [ {name:"orange", qty: 1}, {name:"orange", qty: 2}, {name:"banana", qty: 4}, {name:"kiwi", qty: 3}, ]; const fruits2 = [ {name:"apple", qty: 6}, {name:"apple", qty: 2} ];
我可以使用过滤器执行此操作,但是然后我必须遍历两次水果。有没有更有效的方法?
partition
函数,该函数根据谓词将项目分为两个数组。使用Array.reduce()
迭代数组,并将谓词应用于每个项目。谓词应返回布尔值。将布尔结果转换为数字将使false
为0,true
为1。使用数字作为子数组的索引将项目推入。您可以使用解构将结果分配给fruit1
和fruit2
。 const partition = (predicate, arr) => arr.reduce((r, o) => {
r[+predicate(o)].push(o);
return r;
}, [[], []]);
const fruits = [{"name":"orange","qty":1},{"name":"orange","qty":2},{"name":"banana","qty":4},{"name":"apple","qty":6},{"name":"kiwi","qty":3},{"name":"apple","qty":2}];
const [fruits1, fruits2] = partition(o => o.name === 'apple', fruits);
console.log(fruits1);
console.log(fruits2);
push
指向一个或另一个数组,具体取决于name
: const fruits = [
{name:"orange", qty: 1},
{name:"orange", qty: 2},
{name:"banana", qty: 4},
{name:"apple", qty: 6},
{name:"kiwi", qty: 3},
{name:"apple", qty: 2}
];
const apples = [];
const others = [];
for (const fruit of fruits) {
(fruit.name === 'apple' ? apples : others).push(fruit);
}
console.log(apples);
如果您必须使用一个数组方法而又不改变外部变量,则可以使用reduce
一次合并为两个数组,但看起来不太可读:const fruits = [ {name:"orange", qty: 1}, {name:"orange", qty: 2}, {name:"banana", qty: 4}, {name:"apple", qty: 6}, {name:"kiwi", qty: 3}, {name:"apple", qty: 2} ]; const [apples, others] = fruits.reduce((a, fruit) => { (fruit.name === 'apple' ? a[0] : a[1]).push(fruit); return a; }, [[], []]); console.log(apples); console.log(others);
forEach()
。您甚至可以使用filter()
数组函数,但是为此您需要使用两次filter()
。因此,使用一个循环将您的复杂性降至最低: const fruits = [
{name:"orange", qty: 1},
{name:"orange", qty: 2},
{name:"banana", qty: 4},
{name:"apple", qty: 6},
{name:"kiwi", qty: 3},
{name:"apple", qty: 2}
];
let fruits1 = [];
let fruits2 = [];
fruits.forEach((fruit) => {
if(fruit.name === 'apple') {
fruits2.push(fruit);
} else {
fruits1.push(fruit);
}
});
console.log('fruits1', fruits1);
console.log('fruits2', fruits2);