Anyone can explain me this situation?
In the second call the function, the result is {cat: 2, cat,cat: 1, dog: 1, frog: 1}.
However, I thought that the result was going to be {cat: 4, dog: 1, frog: 1}.
What's going on here?
var animals = ['cat', 'cat', ['cat'], 'dog', 'frog'];
var otherAnimals = ['cat', 'cat', ['cat', 'cat'], 'dog', 'frog'];
function reducingArrays(arraySource) {
var countedData = arraySource.reduce(function(allItems, item) {
if (item in allItems) {
allItems[item]++;
} else {
allItems[item] = 1;
}
return allItems;
}, {});
console.log(countedData);
}
reducingArrays(animals); // {cat: 3, dog: 1, frog: 1}
reducingArrays(otherAnimals); // {cat: 2, cat,cat: 1, dog: 1, frog: 1}
// What I expected: {cat: 4, dog: 1, frog: 1}
['cat']is cast to'cat'.['cat','cat']is cast to'cat,cat'. You're using arrays as object keys, which converts them to strings. You want some kind of recursive function.[].concat(...arr)to flatten an array.