1

Count the occurrences of each element inside an array using reduce. My code was wrong!

My code:

function countOccurrences(arr) {
  return arr.reduce(function(a, b){
    var count = 0;
    for(var i = 0; i < arr.length; i++){
      if (arr[i] == b) {
        return count + 1;
      }
    }
  }, '');
}

console.log(countOccurrences(['a', 'b', 'c', 'b', 'a']));

Expect:

// { 
//   a: 2, 
//   b: 2, 
//   c: 1 
// }

Thanks so much!

R3tep
  • 12,512
  • 10
  • 48
  • 75
Hoang Dinh
  • 157
  • 1
  • 10
  • _"My code didn't work effectively"_ - And that means what, exactly? – Andreas May 06 '19 at 14:47
  • 2
    Possible duplicate of [Counting the occurrences / frequency of array elements](https://stackoverflow.com/questions/5667888/counting-the-occurrences-frequency-of-array-elements) and [How to count the number of occurrences of each item in an array?](https://stackoverflow.com/questions/11649255) – adiga May 06 '19 at 14:48
  • Your `initialValue` is an empty string, you are trying to return a number inside `reduce` callback and you are expecting an object as output. Please go through [`reduce`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce) thoroughly before using it – adiga May 06 '19 at 14:49

3 Answers3

4

You are making two mistakes:

  • You the initial value of a to empty string by passing '' as second argument.
  • You don't need to loop again inside reduce(). reduce() it iterates through all the elements.

function countOccurrences(arr) {
  return arr.reduce(function(a, b){
    a[b] = a[b] + 1 || 1
    return a;
  }, {});
}
console.log(countOccurrences(['a', 'b', 'c', 'b', 'a']));

A on-liner using Arrow Functions will be

const count = (arr) => arr.reduce((ac,a) => (ac[a] = ac[a] + 1 || 1,ac),{})

console.log(count(['a', 'b', 'c', 'b', 'a']));
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
0

You can use reduce to loop thru the array and summarize it into an object. Initiate the accumulator as an object {}. Check if each letter exist as property in the accumulator. Initiate as 0 if not and add 1.

function countOccurrences(arr) {
  return arr.reduce((a, b) => (a[b] = (a[b] || 0) + 1, a), {});
}

let result = countOccurrences(['a', 'b', 'c', 'b', 'a']);
console.log(result);
Eddie
  • 26,593
  • 6
  • 36
  • 58
0

In the reduce pass an empty object as initial accumulator. In this object check if there exist a relevenat key. If so then increase the count else create the key and assign value to it

function countOccurrences(arr) {

  return arr.reduce(function(acc, curr) {
    if (acc[curr]) {
      acc[curr] += 1;
    } else {
      acc[curr] = 1
    }
    return acc;

  }, {})

}

console.log(countOccurrences(['a', 'b', 'c', 'b', 'a']));
brk
  • 48,835
  • 10
  • 56
  • 78