基于属性[closed]将所有对象分离并分组到一个新数组中

问题描述 投票:-3回答:3
我有一个对象数组,我需要将其拆分为2个数组,其中一个对象的所有对象都与特定属性匹配,另一个对象与其余对象匹配。

例如,这是一个示例数组:

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} ];

我可以使用过滤器执行此操作,但是然后我必须遍历两次水果。有没有更有效的方法?
javascript arrays loops object grouping
3个回答
1
投票
您可以创建一个partition函数,该函数根据谓词将项目分为两个数组。使用Array.reduce()迭代数组,并将谓词应用于每个项目。谓词应返回布尔值。将布尔结果转换为数字将使false为0,true为1。使用数字作为子数组的索引将项目推入。您可以使用解构将结果分配给fruit1fruit2

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);

1
投票
它的功能较少,但是您可以将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);

0
投票
您可以使用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);
© www.soinside.com 2019 - 2024. All rights reserved.