gpt4 book ai didi

javascript - 如何查找包含出现次数最多的值的对象的数组内的值(深度模式)?

转载 作者:行者123 更新时间:2023-11-28 14:25:57 25 4
gpt4 key购买 nike

假设我有一个包含如下对象的数组:

const persons = [
{
name: "Erik",
age: 45
},
{
name: "Bob",
age: 37
},
{
name: "Erik",
age: 28
},
{
name: "Jasper",
age: 29
},
{
name: "Erik",
age: 34
}
];

如何根据出现次数最多的键查找值?在此示例中,当将 name 作为键传递时,该键将为 Erik

类似这样的事情:

const deepMode = (array, key) => {
// Perhaps something with .reduce?
}

当调用时,它应该返回:

deepMode(persons, "name"); // Returns "Erik"

最佳答案

您可以选择 Map ,计算出现次数并减少键/值对以获得最大值。返回 key 而不再次迭代。

const
deepMode = (array, key) => Array
.from(array.reduce((m, o) => m.set(o[key], (m.get(o[key]) || 0) + 1), new Map))
.reduce((a, b) => a[1] > b[1] ? a : b)[0],
persons = [{ name: "Erik", age: 45 }, { name: "Bob", age: 37 }, { name: "Erik", age: 28 }, { name: "Jasper", age: 29 }, { name: "Erik", age: 34 }];

console.log(deepMode(persons, 'name'));

关于javascript - 如何查找包含出现次数最多的值的对象的数组内的值(深度模式)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53260512/

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