Languages
[Edit]
EN

JavaScript - count occurrences of array elements

3 points
Created by:
Rubi-Reyna
677

In this article, we would like to show you how to count occurrences of array elements using JavaScript.

Practical examples

Example 1

In this example, we create a reusable function that counts occurrences and stores them in the object.

// ONLINE-RUNNER:browser;

const countElements = (array) => {
    const counts = {};
    for (const element of array) {
        const count = counts[element] ?? 0;  // or:  const count = counts[element] || 0;
        counts[element] = count + 1;
    }
    return counts;
};


// Usage example:

const input = ['a', 'a', 'a', 'b', 'b', 'c'];
const counts = countElements(input);

for (const key in counts) {
    console.log(key + ' ' + counts[key]);
}

 

Example 2

In this example, we create a reusable function that counts occurrences and stores them in the object. Keys in the object are acheved using keyGetter function which lets to use a composite keys (composed of multiple properties).

// ONLINE-RUNNER:browser;

const countElements = (array, keyGetter) => {
    const counts = {};
    for (const element of array) {
        const key = keyGetter(element);
        const count = counts[key] ?? 0;  // or:  const count = counts[key] ?? 0;
        counts[key] = count + 1;
    }
    return counts;
};


// Usage example:

const input = [
    { x: 1, y: 1 },
    { x: 1, y: 1 },
    { x: 1, y: 2 },
    { x: 2, y: 2 },
    { x: 2, y: 2 }
];

const counts = countElements(input, (element) => '(' + element.x + ',' + element.y + ')');

for (const key in counts) {
    console.log(key + ': ' + counts[key]);
}

 

See also

  1. JavaScript - count character occurrences in text

  2. JavaScript - ECMAScript / ES versions and features

References

  1. for...of - JavaScript | MDN
  2. for...in - JavaScript | MDN

Alternative titles

  1. JavaScript - count frequency of array elements
  2. JavaScript - count duplicate values in array
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join