[英]Group by count of objects within an array in Vanilla Javascript
I have an array of objects: 我有一个对象数组:
[{person:101, year: 2012}, {person:102, year: 2012}, {person:103, year: 2013}]
And I want to be able to return an aggregate count for each year (much like a group by in SQL would achieve) in the format of: 而且我希望能够以以下格式返回每年的总计计数(非常类似于SQL中的by by):
[{year: 2012, count:2}, {year: 2013, count:1}]
What is the best way to achieve this in Vanilla Javascript? 用Vanilla Javascript实现此目的的最佳方法是什么?
You need to use simple for like below : 您需要像下面这样使用simple:
var data = [{person:101, year: 2011},
{person:102, year: 2012},
{person:103, year: 2011}];
var result = {},
i;
for(i=0; i < data.length; i++){
let year = data[i].year;
if(typeof result[year] === 'undefined'){
result[year] = 1;
}
else{
result[year] = result[year] + 1;
}
}
console.log(result);
As others have mentioned, an object would be a better fit for aggregating the data. 正如其他人提到的那样,对象将更适合于汇总数据。 You could use a normal loop, or reduce to do it: 您可以使用常规循环,也可以使用减少循环来完成:
var data = [{person:101, year: 2012}, {person:102, year: 2012}, {person:103, year: 2013}]; var yearCounts = data.reduce(function (result, person) { var currentCount = result[person.year] || 0; result[person.year] = currentCount + 1; return result; }, {}); console.log(yearCounts);
If you really need it as an array, you could the loop over the object and convert it to an array: 如果确实需要它作为数组,则可以遍历对象并将其转换为数组:
var data = [{person:101, year: 2012}, {person:102, year: 2012}, {person:103, year: 2013}]; var yearCounts = data.reduce(function (result, person) { var currentCount = result[person.year] || 0; result[person.year] = currentCount + 1; return result; }, {}); var year, yearCountArray = []; for (year in yearCounts) { if (yearCounts.hasOwnProperty(year)) { yearCountArray.push({ year: year, count: yearCounts[year] }); } } console.log(yearCountArray);
Use a generic group by key reducer that will count the number of items in each group. 使用通用的按组归约密钥减少器将计算每个组中的项目数。 I will take inspiration from a previous answer of mine . 我将从以前的回答中得到启发。 This function will return another function that act as a reducer, but you can always give it the key that you want as a parameter. 该函数将返回另一个充当约简器的函数,但是您始终可以为其提供所需的键作为参数。
const groupByCounter = key => (result,current) => { const item = Object.assign({},current); if (typeof result[current[key]] == 'undefined'){ result[current[key]] = 1; }else{ result[current[key]]++; } return result; }; const data = [{person:101, year: 2012}, {person:102, year: 2012}, {person:103, year: 2013}]; const group = data.reduce(groupByCounter('year'),{}); console.log(group);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.