我正在努力了解如何正确地使用Array.reduce()来汇总摘要/报告数据(即分组计数)。我通常通过用forEach
遍历数据并构建对象来手动执行此操作,但是我觉得链接map和reduce必须成为一种更优雅,更实用的方法;我只是无法弄清楚如何正确执行此操作。
这是我的实验带给我的地方:
const articleData = [
{newsSource: "AP", title: "Some article.", category: "World"},
{newsSource: "BBC", title: "Some article.", category: "Politics"},
{newsSource: "CBS", title: "Some article.", category: "Sports"},
{newsSource: "CNN", title: "Some article.", category: "Finance"},
{newsSource: "CNN", title: "Another article.", category: "Politics"},
{newsSource: "NBC", title: "Some article.", category: "Politics"},
{newsSource: "NBC", title: "Another article.", category: "Finance"},
{newsSource: "Reuters", title: "Some article.", category: "World"},
{newsSource: "Reuters", title: "Another article.", category: "Politics"},
{newsSource: "Reuters", title: "Yet another article.", category: "Finance"}
];
// I want to set reportData to be the result of the chained map/reduce
// ...not declare it here and assemble it within the functions below
let reportData = {};
articleData.map((item, index) => {
if (item.newsSource) return item.newsSource;
})
.reduce((acc, newsSource) => {
if (!reportData[newsSource]) {
reportData[newsSource] = 1;
} else {
reportData[newsSource] = reportData[newsSource] + 1;
}
return (acc, reportData);
});
console.log(reportData);
// Expected output:
// { AP: 1, BBC: 1, CBS: 1, CNN: 2, NBC: 2, Reuters: 3 }
这里有很多问题。 (最重要的是它跳过了第一个数据元素!我认为我理解为什么,但是我不知道如何解决它。)但是最重要的是,我想了解如何构造我的[ C0]函数,因此我不更改其中的reduce
,而是返回“预期输出”下显示的正确结构化的数据。
减少平面阵列对我来说很明显,但是一旦我处理了超出该深度的任何结构,我都会感到困惑。
您可以通过拳头值在reportData = articleData.reduce(function(c, a) {
c[a.newsSource] = (c[a.newsSource] || 0) + 1;
return c;
}, {});
console.log(reportData);
方法的const articleData = [{
newsSource: "AP",
title: "Some article.",
category: "World"
},
{
newsSource: "BBC",
title: "Some article.",
category: "Politics"
},
{
newsSource: "CBS",
title: "Some article.",
category: "Sports"
},
{
newsSource: "CNN",
title: "Some article.",
category: "Finance"
},
{
newsSource: "CNN",
title: "Another article.",
category: "Politics"
},
{
newsSource: "NBC",
title: "Some article.",
category: "Politics"
},
{
newsSource: "NBC",
title: "Another article.",
category: "Finance"
},
{
newsSource: "Reuters",
title: "Some article.",
category: "World"
},
{
newsSource: "Reuters",
title: "Another article.",
category: "Politics"
},
{
newsSource: "Reuters",
title: "Yet another article.",
category: "Finance"
}
];
reportData = articleData.reduce(function(c, a) {
c[a.newsSource] = (c[a.newsSource] || 0) + 1;
return c;
}, {});
console.log(reportData);
中累积。您可以在2nd param
功能中跳过值或reduce
值。
manipulate