我正在尝试解决这个小问题,我需要在哪里使用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
// }
如您所见,您需要一个对象作为数组项目计数的结果集。
为了获得结果,您可以采用默认值 0 加 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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)