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.
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;
}
*/
}