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}
You can convert single element to array:
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) {
var arr = Array.isArray(item) ? item : [item];
allItems[arr[0]] = (allItems[arr[0]] || 0) + arr.length;
return allItems;
}, {});
console.log(countedData);
}
reducingArrays(animals);
reducingArrays(otherAnimals);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With