JavaScript 使用 reduce 从数组创建带计数的对象
JavaScript using reduce to create object with counts, from array
我正在尝试解决这个小问题,我需要使用 reduce
创建一个包含每个项目计数的对象。
我以为我了解 reduce
的工作原理,使用一个函数将多个值缩减为一个,但我无法弄清楚这是如何工作的。
有什么想法或建议吗?非常感谢。
// var people = ['josh', 'dan', 'sarah', 'joey', 'dan', 'josh', 'francis', 'dean'];
// can reduce be used to get:
// {
// josh: 2,
// dan: 2,
// sarah: 1,
// joey: 1,
// francis: 1,
// dean: 1
// }
如您所见,您需要一个对象作为结果集来计算数组的项目数。
为了得到结果,您可以使用默认值零来加一来计算实际值,而您使用给定的名称作为 属性 来计算。
var people = ['josh', 'dan', 'sarah', 'joey', 'dan', 'josh', 'francis', 'dean'],
counts = people.reduce(function (c, p) {
c[p] = (c[p] || 0) + 1;
return c;
}, Object.create(null));
console.log(counts);
const groupedByName = people.reduce((obj, person) => {
const count = obj[person] || 0
return { ...obj, [person]: count + 1 }
}, {})
工作codepen
我正在尝试解决这个小问题,我需要使用 reduce
创建一个包含每个项目计数的对象。
我以为我了解 reduce
的工作原理,使用一个函数将多个值缩减为一个,但我无法弄清楚这是如何工作的。
有什么想法或建议吗?非常感谢。
// var people = ['josh', 'dan', 'sarah', 'joey', 'dan', 'josh', 'francis', 'dean'];
// can reduce be used to get:
// {
// josh: 2,
// dan: 2,
// sarah: 1,
// joey: 1,
// francis: 1,
// dean: 1
// }
如您所见,您需要一个对象作为结果集来计算数组的项目数。
为了得到结果,您可以使用默认值零来加一来计算实际值,而您使用给定的名称作为 属性 来计算。
var people = ['josh', 'dan', 'sarah', 'joey', 'dan', 'josh', 'francis', 'dean'],
counts = people.reduce(function (c, p) {
c[p] = (c[p] || 0) + 1;
return c;
}, Object.create(null));
console.log(counts);
const groupedByName = people.reduce((obj, person) => {
const count = obj[person] || 0
return { ...obj, [person]: count + 1 }
}, {})
工作codepen