gpt4 book ai didi

Javascript/ES2015,计算出现次数并存储为数组中的对象

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

我正在从 JSON 提要中提取数据,并试图计算每个名称 (name_class) 出现的次数。

我想返回一个对象数组,格式如下,其中count是指名字出现的次数:

myArray = [{name:"John", count: 5}, {name: "Sarah", count: 2}, {name: "Oliver", count: 3}];

到目前为止我有以下内容,但这不计算出现的次数,它只是将另一个对象添加到数组中;

   let namestUi = {
renderNames(names){
var counter2 = [];
let namesFound = names.map((name) => {
let {name_class} = name;

if(counter2.name == name_class){
counter2.count++;
} else { counter2.push({name: name_class, count: 1}); }
});
console.log(counter2);
return namesFound;
}
};

这是构建对象数组,但不计算出现的次数。

最佳答案

function count(names){
// Count occurrences using a map (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map)
let map = new Map();
for (let name of names) {
map.set(name, (map.get(name) || 0) + 1);
}

// Transform to array of { name, count }
let result = [];
for (let [name, count] of map) {
result.push({name: name, count: count});
}

return result;
}

count(["a", "b", "c", "a", "b", "a"])
// [{"name":"a","count":3},{"name":"b","count":2},{"name":"c","count":1}]

关于Javascript/ES2015,计算出现次数并存储为数组中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39986230/

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