Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird behavior of reduce method in Javascript

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}
like image 379
didaquis Avatar asked May 15 '26 08:05

didaquis


1 Answers

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); 
like image 192
Faly Avatar answered May 17 '26 21:05

Faly



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!