gpt4 book ai didi

javascript - 如何获取现有数组中特定对象的计数数组?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:59:37 25 4
gpt4 key购买 nike

我有一个这样的对象数组:

[
{
importantKey: 'x',
foo: 'bar',
...
},
{
importantKey: 'y',
foo: 'bar',
...
},
{
importantKey: 'z',
foo: 'bar',
...
},
{
importantKey: 'x',
foo: 'bar',
...
},
{
importantKey: 'y',
foo: 'bar',
...
},
{
importantKey: 'z',
foo: 'bar',
...
},
...
]

还有另一个具有importantKey值的数组:

keysArray = [x, y, z]

我如何获得一个数组,其中的值是所有对象的计数,这些对象的每个 importantKey 的顺序与 keysArray 相同?所以最终的结果是:

[ numberOfObjectsWithKeyX, numberOfObjectsWithKeyY, numberOfObjectsWithKeyZ ]

对于这个例子,结果将是:

[2, 2, 2]

同时 keysArray 是动态生成的,所以 xyz 不能硬编码。

最佳答案

你可以这样做:

keysArray.map(key => values.filter(v => v.importantKey === key).length);

基本上,您在 keysArray 上调用 map(),这将为它创建一个并行数组,无论 map() 吐出什么值.

对于该值,您只需调用 values.filter() 并仅过滤掉具有适当键的内容,然后只需检查长度即可获得计数。

const values = [
{
importantKey: 'x',
foo: 'bar'
},
{
importantKey: 'y',
foo: 'bar'
},
{
importantKey: 'y',
foo: 'bar'
},
{
importantKey: 'x',
foo: 'bar'
},
{
importantKey: 'y',
foo: 'bar'
},
{
importantKey: 'z',
foo: 'bar'
}
];

const keys = ['x', 'y', 'z'];

const result = keys.map(key => values.filter(v => v.importantKey === key).length);

console.log(result);

关于javascript - 如何获取现有数组中特定对象的计数数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43686999/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com