You are currently viewing 5 Ways to Count Number of Occurrences in Javascript Array

5 Ways to Count Number of Occurrences in Javascript Array

Javascript Count Number of Occurrences in Array

In this article, we will see how to count number of occurrences in javascript array.

What is javascript array occurrences?

If the same value or element occurs one or more times in an array, it is called javascript array occurrences. Any type of data such as integers, characters, strings, etc. that appears repeatedly in a array, it is considered an occurrence. For example:

const myNum= [1, 2, 3, 3, 4, 3];
const myChar = ['a', 'b', 'a', 'c'];
const myStr = ["red", "blue", "green", "red"];
  • In this example, the number 3 appears three times in the variable ‘myNum’, which means it has three occurrences within the array.
  • Then the variable ‘myChar’ has character type of data, the character ‘a’ appears two times, which means it has two occurrences within the array.
  • The variable ‘myStr’ has Sting type of data, the String ‘red’ appears two times, which means it has two occurrences within the array.

5 ways to count number of occurrences

1. Using reduce() method:

In this method, we use an object to keep track of the counts:

let arr = [1, 2, 3, 2, 1, 3, 1];

let counts = arr.reduce(function (obj, item) {
  if (!obj[item]) {
    obj[item] = 0;
  }
  obj[item]++;
  return obj;
}, {});

console.log(counts);

 // Output: 1: 3, 2: 2, 3: 2}
  1. In this example, we have created array ‘arr’ with 7 elements.
  2. Then we use the ‘reduce()‘ function to iterate over each element in the ‘arr’ array. We have called the callback function on each element. We need to pass two parameters to the callback function.
  3. The first parameter as ‘obj’ object and the second as an ‘item’ value from the ‘arr’ array. The ‘obj’ object is the accumulator that accumulates the results of the reduction, and it is initialized as an empty object like ‘{}’. And the ‘item’ is the current element being processed.
  4. Then we check the condition, if current ‘item’ exists as in object ‘obj’. If it doesn’t exist, the line initializes the property with a value of 0.
  5. We increments the value of the property by 1 using increment operator ‘++’ with the key equal to the current ‘item’ value, like ‘obj[item]++’.
  6. Finally, we returned the object ‘obj’, which is used as the accumulator in the next iteration of ‘reduce’ function and logged the “counts”.
READ ALSO  Easy Way to Escape Double Quote in JavaScript with Example

We got the output, which is the value of ‘counts’ object. It shows the value of ‘arr’ first and then number of occurrences.

2. Using a for loop

It is one of the easiest way to find number of occurrences in array. In this method, we used one ‘for’ loop and if/else statement.

let arr = ['a', 'b', 'a', 'c', 'b', 'a'];
let counts = {};

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

//output : {a:3, b:2, c:1}
  1. Here, we have created an character array “arr” with 6 elements.
  2. Then we initialized the object ‘counts’ to empty {}. It is used to keep track of the counts of each element in the array.
  3. We create for loop and set the iteration to array length using length() function. If the array have 6 elements, so the loop will run 6 times.
  4. Then we check the condition using ‘if’ statement inside the loop, if it exists as a property in the counts object. If it does, we increment its count by 1. If it doesn’t, we add it to the object with a count of 1.
  5. Finally, we logged the object ‘counts’. So, in this case, counts would be {a:3, b:2, c:1}}.

3. Using forEach() method

In this method, we use the forEach() method with ternary operator.

let myStr = ["red", "blue", "green", "red", "blue"];
let counts = {};

myStr.forEach(function (item) {
counts[item] = counts[item] ? counts[item] + 1 : 1;
});

console.log(counts);

// Output: {red: 2, blue: 2, green: 1}
  1. In this above example code, we have created an empty object {} called ‘counts’.
  2. Then we created forEach() mehtod on the array to iterate over each element.
  3. Inside the function, we check the condition if it exists as a property in the ‘counts’ object for each element. If the condition is true, we increment its count by 1. If the condition is false, we add it to the object with a count of 1.
  4. After finished the forEach() method, we logged the object ‘counts’.
READ ALSO  How to Print Prime Numbers in JavaScript

4. Using Map() object

let arr = [1, 2, 3, 2, 1, 3, 1];
let counts = new Map();

for (let i = 0; i < arr.length; i++) {
  let count = counts.get(arr[i]) || 0;
  counts.set(arr[i], count + 1);
}

console.log(counts);

// Output: Map(3) {1 => 3, 2 => 2, 3 => 2}
  1. In this example above, we initialize new empty Map() called ‘counts’.
  2. Then we create ‘for’ loop and set the condition “< arr.length”. The loop will run until the arraylength() value is returned for the ‘i’ variable.
  3. We use the get() method on the ‘counts’ Map() to get its count for each element. If the count is undefined, we initialize it to 0.
  4. Then we incremented the variable ‘count’ by 1 and use set() method to update count in ‘counts’ Map().
  5. Finally, we logged the ‘counts’ outside the loop.

5. Using filter() method

In this method, the filter() method doesn’t directly count the number of occurrences of a particular value in an array. But you can achieve this using the┬ácombination with other array methods .

let arr = [3, 2, 6, 4, 3, 2, 3];
let num = 3;
let count = arr.filter(x => x === num).length;

console.log(count);

// Output : 3
  1. Here, we have created a variable called ‘num’ and initialized the value we want to find the occurrence. I want to find the occurrence of 3, so we initialize 3.
  2. Then created new array ‘count’ using the filter() method and compare each element of ‘arr’ with the value 3
  3. We got the ouput 3, which means the number 3 appears three times in the array ‘arr’.

Conclusion

These are the main 5 ways to find the number of occurrences in array. I recommend the ‘for’ loop and forEach() method, because it is very easy and most of the programmers also using this methtod.

Leave a Reply