Sling Academy
Home/JavaScript/JavaScript: Count the occurrences of elements in an array

JavaScript: Count the occurrences of elements in an array

Last updated: March 08, 2023

This concise, straight-to-the-point article shows you 3 different ways to count the occurrences of elements in a given array in JavaScript.

Using a loop

In the example below, we will use a for loop to iterate over the array and update the count for each element. We will create an object to store the count and print it out at the end.

Example:

const array = [
  'apple',
  'banana',
  'slingacademy.com',
  'apple',
  'slingacademy.com',
];
const count = {};

for (let i = 0; i < array.length; i++) {
  const element = array[i];
  count[element] = (count[element] || 0) + 1;
}

console.log(count);

Output:

{ apple: 2, banana: 1, 'slingacademy.com': 2 }

Using the reduce() method

In the following example, we will use the reduce() method to iterate over a given array and create an object that stores the count of each element.

Example:

const array = [
  'apple',
  'banana',
  'slingacademy.com',
  'apple',
  'slingacademy.com',
];

const count = array.reduce((acc, curr) => {
  acc[curr] = (acc[curr] || 0) + 1;
  return acc;
}, {});

console.log(count);

Output:

{ apple: 2, banana: 1, 'slingacademy.com': 2 }

Using the Array.filter() method and a callback function

In the example below, we will define a function called countOccurrences() that takes an array and a value as parameters and returns how many times that value appears in that array. The function uses the Array.filter() method to create a new array with only elements that are equal to the value parameter. Then it returns the length of this new array, which is equal to the number of occurrences of that value in that array.

The code:

// Define a function that takes an array and a value as parameters 
// and returns how many times that value appears in that array 
const countOccurrences = (array, value) => {
  var filteredArray = array.filter(function (element) {
    return element === value;
  });

  return filteredArray.length;
}

const arr = ['a', 'b', 'c', 'a', 'b', 'a', 'a', 'b', 'c', 'a', 'c', 'c'];
for (var i = 0; i < [...new Set(arr)].length; i++) {
  var uniqueElement = [...new Set(arr)][i];

  console.log(
    uniqueElement +
      ' occurs ' +
      countOccurrences(arr, uniqueElement) +
      ' times'
  );
}

Output:

a occurs 5 times
b occurs 3 times
c occurs 4 times

Conclusion

You’ve learned more than one technique to count the occurrences of elements in an array. This knowledge will help you in various situations, such as:

  • Grouping items in a shopping cart: When working with e-commerce applications, we may need to group items in a shopping cart based on their type, size, or color. We can use the methods described above to count the occurrences of each item and then group them accordingly.
  • Analyzing product reviews: If we have an array of product reviews where each review is a string, we can use the methods described above to count the occurrences of positive and negative words in the reviews. This is useful for tasks such as analyzing customer sentiment towards a product.

Done. Happy coding & have a nice day!

Next Article: Create JavaScript array of random elements with given length

Previous Article: JavaScript: 5 Ways to Concatenate Multiple Arrays

Series: Working with Arrays in JavaScript

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration