如何访问减少数组中重复的第零个元素 [英] how to access zeroth element in reduce to count repeats in an array
问题描述
根据节点学校的想法,我试图使用 reduce
来计算字符串在数组中重复的次数.
On the whim of node school, I am trying to use reduce
to count the number of times a string is repeated in an array.
var fruits = ["Apple", "Banana", "Apple", "Durian", "Durian", "Durian"],
obj = {};
fruits.reduce(function(prev, curr, index, arr){
obj[curr] ? obj[curr]++ : obj[curr] = 1;
});
console.log(obj); // {Banana: 1, Apple: 1, Durian: 3}
正在工作.由于某些原因, reduce
似乎跳过了第一个元素.我不知道为什么第一次通过数组 index
是 1
.我尝试加入一些逻辑,例如 if(index === 1){//将'prev'作为'obj'}的属性
.但这似乎确实令人费解.我敢肯定,这不是节点学校要我解决这个问题的方式.但是,我想知道什么是访问要减少的数组中第零个元素的好方法.为什么这个第零个元素似乎被归约过程忽略了?我想我可以在回调后传入 fruits [0]
,所以我最初从该值开始.访问该第零个元素的最佳方法是什么?
is sort of working. For some reason, reduce
seems to skip the first element. I don't know why. Its first time through the array, index
is 1
. I tried putting in some logic like, if (index === 1){//put 'prev' as a property of 'obj'}
. But that seems really convoluted. I'm certain that this is not how node school wants me to solve this problem. However, I wonder what's a good way to access the zeroth element in the array you're reducing. Why is this zeroth element seemingly ignored by the reduction procedure? I guess I could pass in fruits[0]
after the callback so I start with that value initially. What's the best way to access this zeroth element?
推荐答案
如果未提供
initialValue
,则previousValue
将等于数组中的第一个值,而currentValue
将等于第二个值
If no
initialValue
was provided, thenpreviousValue
will be equal to the first value in the array andcurrentValue
will be equal to the second.
此外,您还必须从函数中返回一个值.该值将在下一次迭代时成为 previousValue
的值.
Additionally, you have to return a value from the function. That value becomes the value of previousValue
on the next iteration.
我建议您携带"聚合器 obj
作为初始值.
I'd suggest you "carry" your aggregator obj
as the initial value.
var fruits = ["Apple", "Banana", "Apple", "Durian", "Durian", "Durian"];
var obj = fruits.reduce(function(carry, fruit){
if(!carry[fruit]) carry[fruit] = 0; // If key doesn't exist, default to 0
carry[fruit]++; // Increment the value of the key
return carry; // Return aggregator for next iteration
}, {});
alert(JSON.stringify(obj));
这是一个简单的图:
fruit carry (before operation) carry (after operation, returned value)
1st iteration: Apple {} {Apple:1}
2nd iteration: Banana {Apple:1} {Apple:1, Banana:1}
3rd iteration: Apple {Apple:1, Banana:1} {Apple:2, Banana:1}
4th iteration: Durian {Apple:2, Banana:1} {Apple:2, Banana:1, Durian:1}
5th iteration: Durian {Apple:2, Banana:1, Durian:1} {Apple:2, Banana:1, Durian:2}
6th iteration: Durian {Apple:2, Banana:1, Durian:2} {Apple:2, Banana:1, Durian:3}
这篇关于如何访问减少数组中重复的第零个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!