[英]Javascript/ES2015, count the number of occurrences and store as objects within an array
I am extracting data from a JSON feed and am trying to count the number of times each name (name_class) occurs.我正在从 JSON 提要中提取数据,并尝试计算每个名称 (name_class) 出现的次数。
I want to return an array of objects in the following format, where count refers to the number of times the name appears:我想以以下格式返回一个对象数组,其中 count 是指名称出现的次数:
myArray = [{name:"John", count: 5}, {name: "Sarah", count: 2}, {name: "Oliver", count: 3}];
So far I have the following, but this does not count the number of occurrences, it simply adds another object to the array;到目前为止,我有以下内容,但这不计算出现次数,它只是将另一个对象添加到数组中;
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;
}
};
This is building the array of objects but not counting the number of occurrences.这是构建对象数组,但不计算出现次数。
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}]
There are some problems in how you use your counter variable.您如何使用计数器变量存在一些问题。 You access properties as if it is a plain object, but you defined it as an array.
您可以像访问普通对象一样访问属性,但您将其定义为数组。 Also your
map
callback function is not returning any value.此外,您的
map
回调函数没有返回任何值。
You could use this code which uses a Map
to key counters by name, and then applies Array.from
to convert that Map to an array of objects as you requested:您可以使用此代码,它使用
Map
来按名称键计数器,然后应用Array.from
将该 Map 转换为您请求的对象数组:
let namestUi = { renderNames(names){ return Array.from( names.reduce( (counters, {name_class}) => counters.set(name_class, (counters.get(name_class) || 0) + 1), new Map() ), ([name, count]) => ({name, count}) ); } }; let result = namestUi.renderNames([ { name_class: "John" }, { name_class: "John" }, { name_class: "Frank" }, { name_class: "John" }, ]); console.log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.