我有一个数组:
people = [
{name: a, group: 1},
{name: b, group: 2},
{name: c, group: 3},
{name: d, group: 2},
{name: e, group: 3},
{name: f, group: 1},
{name: g, group: 1},
];
我需要找到第2组和第3组中的所有人员。 所需的输出:
filteredPeople = [
{name: b, group: 2},
{name: c, group: 3},
{name: d, group: 2},
{name: e, group: 3},
];
也可能是其他组(用于搜索的组可能会更改)。
我该怎么做?
答案 0 :(得分:1)
您可以使用.filter()
和.includes()
方法来获得所需的输出:
const data = [
{name: 'a', group: 1}, {name: 'b', group: 2}, {name: 'c', group: 3},
{name: 'd', group: 2}, {name: 'e', group: 3}, {name: 'f', group: 1},
{name: 'g', group: 1}
];
const groups = [2, 3];
const result = data.filter(({ group }) => groups.includes(group));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:1)
filter
和includes
在这里完成工作。我们使用rest运算符(这为我们提供了一个可以在其中应用includes
的数组)。因此,您可以在函数调用中放入任意数量的组,以便在过滤时保持灵活。
let people = [{name: "a",group:1},{name: "b",group:2},{name: "c",group:3},{name:"d",group:2},{name:"e",group:3},{name:"f",group:1},{name:"g",group:1}];
let filterGroups = (arr, ...groups) => arr.filter(o => groups.includes(o.group));
console.log(filterGroups(people, 2, 3));
答案 2 :(得分:0)
使用Array.prototype.filter()和表达式2 === group || group === 3
const data = [{name: 'a', group: 1}, {name: 'b', group: 2}, {name: 'c', group: 3}, {name: 'd', group: 2}, {name: 'e', group: 3}, {name: 'f', group: 1}, {name: 'g', group: 1}];
const result = data.filter(({ group }) => group === 2 || group === 3);
console.log(result);