How to find frequency of a number in an array?

How to find frequency of a number in an array?
0

#1

Example output for [ 2, 20, 11, 10, 5, 14, 47, 23, 20, 12, 11, 10 ]
Frequency of 2: 1
Frequency of 20: 2
Frequency of 11: 2
Frequency of 10: 2
Frequency of 2: 1
Frequency of 14: 1
Frequency of 47: 1
Frequency of 23: 1
Frequency of 12: 1


#2
let arr = [ 2, 20, 11, 10, 5, 14, 47, 23, 20, 12, 11, 10 ];

let freq = {};

for (let i = 0; i < arr.length; i++) {
	if (freq[arr[i]] === undefined) {
  	freq[arr[i]] = 1;
  } else {
  	freq[arr[i]] += 1;
  }
}

for (var prop in freq) {
  console.log('Frequency of ' + prop, '=', freq[prop]);
}

Something like this seems to work, put the values like a key-value pair in an object, then you can loop through that object to print out the pairs.


#3
function frequencyOfNumber(arr) {
  const result = {};

  arr.forEach(num => {
    if (!result[num]) result[num] = 1;
    else result[num]++;
  });

  arr.forEach(num => {
    console.log('Frequency of', num, result[num]);
  })
}

frequencyOfNumber([2, 20, 11, 10, 5, 14, 47, 23, 20, 12, 11, 10]);