查找两个数组之间匹配的对象值的计数

时间:2019-07-14 20:44:25

标签: javascript arrays object

我正在尝试从(对象的)两个数组中获取匹配数据的计数。我想为每个组找到activetrue的所有实例,然后创建一个新的数组,该数组列出事物数组中匹配项的数量。

const groups = [
  {id: 234},
  {id: 423},
  {id: 474},
  {id: 864}
];

const things = [
  {id: 1, active: false, group: 234},
  {id: 2, active: true, group: 234},
  {id: 3, active: false, group: 234},
  {id: 4, active: true, group: 423},
  {id: 5, active: true, group: 423},
  {id: 6, active: false, group: 423}
];

我想要得到的结果是来自things数组的组ID 活动中事物的数量。我可以使用过滤器返回活动项,但是如何获得计数并获得新的数组,如下面的输出所示?

我希望最终结果看起来像这样:

[
  {group: 234, active: 1},
  {group: 423, active: 2}
];

3 个答案:

答案 0 :(得分:1)

您可以按照以下步骤进行操作,首先过滤,然后按有效值对它们进行分组。

const groups = [{
  id: 234
}, {
  id: 423
}, {
  id: 474
}, {
  id: 864
}]

const things = [{
  id: 1,
  active: false,
  group: 234
}, {
  id: 2,
  active: true,
  group: 234
}, {
  id: 3,
  active: false,
  group: 234
}, {
  id: 4,
  active: true,
  group: 423
}, {
  id: 5,
  active: true,
  group: 423
}, {
  id: 6,
  active: false,
  group: 423
}];

const temp = things.filter(thing => {
  return groups.find(group => group.id == thing.group && thing.active)
}).reduce((mem, cur) => {
  mem[cur.group] = (mem[cur.group] || 0) + 1;
  return mem;
}, {});

const result = Object.keys(temp).map(key => ({
  'group': key,
  active: temp[key]
}));

console.log(result);

答案 1 :(得分:1)

您可以过滤,过滤和计数项目。

const
    groups = [{ id: 234 }, { id: 423 }, { id: 474 }, { id: 864 }]
    things = [{ id: 1, active: false, group: 234 }, { id: 2, active: true, group: 234 }, { id: 3, active: false, group: 234 }, { id: 4, active: true, group: 423 }, { id: 5, active: true, group: 423 }, { id: 6, active: false, group: 423 }],
    groupsSet = new Set(groups.map(({ id }) => id)),
    result = Array.from(
        things
            .filter(({ active }) => active)
            .filter(({ group }) => groupsSet.has(group))
            .reduce((m, { group }) => m.set(group, (m.get(group) || 0) + 1), new Map),
        ([group, active]) => ({ group, active })
    );

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:1)

一个可能的解决方案是使用Array.reduce()生成一个Timer u = Application.OpenForms["Form1"].Controls["SpeakTime"] as Timer; 个所需组的object个。然后,在第二步上,您可以使用Array.map()获得所需的输出。

active
const groups = [{id: 234}, {id: 423}, {id: 474}, {id: 864}];

const things = [
  {id: 1, active: false, group: 234},
  {id: 2, active: true, group: 234},
  {id: 3, active: false, group: 234},  
  {id: 4, active: true, group: 423},
  {id: 5, active: true, group: 423},  
  {id: 6, active: false, group: 423}
];

let groupsSet = new Set(groups.map(g => g.id));

let res = things.reduce((acc, {group, active}) =>
{
    if (active && groupsSet.has(group))
        acc[group] = (acc[group] || 0) + 1;

    return acc;
}, {});

res = Object.entries(res).map(([group, active]) => ({group, active}));
console.log(res);