How to count number of elements and return it in object

How to count number of elements and return it in object
0

#1

In an array of var arr = [2,2,2,2,3,3,4], how can I create a function that counts the number of occurrences of each number in the array and return it in an object?

For ex: [ 2 : 4, 3 : 2, 4 : 1];

The function should take only one parameter, which is the array.

I’ve been trying to figure answer out on my own for like last 5 hrs but can’t figure it out.


#2

#3

Thanks. One bad thing about the page you linked is that it gives you answers, but it does not explain why.

a = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];
result = { };
for(var i = 0; i < a.length; ++i) {
if(!result[a[i]])
result[a[i]] = 0;
++result[a[i]];
}

Do you know why this works and what each line of code is supposed to do?


#4
const a = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];
const result = {};

for (let i = 0; i < a.length; ++i) { // loop over array

  if (!result[a[i]]){  // if no key for that number yet
    result[a[i]] = 0;  // then make one
  }
    
  ++result[a[i]];     // increment the property for that number
  console.log(result)
}

/*
value of result after each loop
{ '5': 1 }
{ '5': 2 }
{ '5': 3 }
{ '2': 1, '5': 3 }
{ '2': 2, '5': 3 }
{ '2': 3, '5': 3 }
{ '2': 4, '5': 3 }
{ '2': 5, '5': 3 }
{ '2': 5, '5': 3, '9': 1 }
{ '2': 5, '4': 1, '5': 3, '9': 1 }
*/


#5

I linked to this answer

var arr = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];
var counts = {};
// looping through your array
for (var i = 0; i < arr.length; i++) {
  var num = arr[i];
  // this is a ternary if statement increasing the count
  // if name(number) exists in your object add 1, else add number with value of 1
  counts[num] = counts[num] ? counts[num] + 1 : 1;
  /*
  Could also be written like this
  if (counts[num]) {
      counts[num] += 1;
  } else {
      counts[num] = 1;
  }
  */
}

#7

Thanks. One more question.

What conditional statement should I use in order to make it say “4 or more” when there are 4 or more number counts for a number?

For example, make it say { ‘2’: ‘4 or more’, ‘4’: 1, ‘5’: 3, ‘9’: 1 }, instead of { ‘2’: 5, ‘4’: 1, ‘5’: 3, ‘9’: 1 }.