Horje
Count occurrences of all items in an array in JavaScript

We will see how to count occurrences of all items in an array in JavaScript. One of the most common methods of doing this is by using the traditional for loop. In JavaScript, we have another modern approach to iterate the array which is by using the forEach method.

Example:

Input: [1,3,4,3,4,1,3,3,3,4]
Output: {"1": 2, "3" : 5, "4" 3}

Counting the occurrences of all the items in an array can be done in the following ways:

Approach 1: Using the Javascript forEach() method

The arr.forEach() method calls the provided function once for each element of the array. The provided function may perform any kind of operation on the elements of the given array. 

Syntax:

array.forEach(callback(element, index, arr), thisValue)

Example: In this example, we will iterate over the elements of an array using the forEach() method, count the number of occurrences of all the elements of the array, and print them in the console.

JavaScript
let arr = [
    'geeks', 2, 'geeks', 2, 'Javascript', 4,
    'Javascript', 5, 'for', 6, 'Javascript', 1,
    'for', 5, 7, 8, 'for'
];

const counter = {};

arr.forEach(ele => {
    if (counter[ele]) {
        counter[ele] += 1;
    } else {
        counter[ele] = 1;
    }
});

console.log(counter)

Output
{
  '1': 1,
  '2': 2,
  '4': 1,
  '5': 2,
  '6': 1,
  '7': 1,
  '8': 1,
  geeks: 2,
  Javascript: 3,
  for: 3
}

Approach 2: Using reduce() method

The Javascript arr.reduce() method is used to reduce the array into a single value and executes the provided function for each value of the array (from left-to-right) and the return value of the function is stored in an accumulator. 

Syntax:

array.reduce( 
function(total, currentValue, currentIndex, arr),
initialValue
)

Example: In this example, we will iterate over the elements of an array using the reduce() method and count the number of occurrences of all the elements of the array and print them in the console.

JavaScript
const arr = [
    'geeks', 2, 'geeks', 2, 'Javascript', 4,
    'Javascript', 5, 'for', 6, 'Javascript', 1,
    'for', 5, 7, 8, 'for'
];

let count = arr.reduce(function (value, value2) {
    return (
        value[value2] ? ++value[value2] :(value[value2] = 1),
        value
    );
}, {});

console.log(count);

Output
{
  '1': 1,
  '2': 2,
  '4': 1,
  '5': 2,
  '6': 1,
  '7': 1,
  '8': 1,
  geeks: 2,
  Javascript: 3,
  for: 3
}

Approach 3: Using filter() method

The JavaScript Array filter() Method is used to create a new array from a given array consisting of only those elements from the given array which satisfy a condition set by the argument method. 

Syntax:

array.filter(callback(element, index, arr), thisValue)

Example: In this example, we will use the array filter() method to check the occurrences of the elements of the array and print them in the console.

JavaScript
const arr = [
    'geeks', 2, 'geeks', 2, 'Javascript', 4,
    'Javascript', 5, 'for', 6, 'Javascript', 1,
    'for', 5, 7, 8, 'for'
];

const itemCounter = (value, index) => {
    return value.filter((x) => x == index).length;
};

console.log(itemCounter(arr, 'geeks'))

Output
2

Approach 4: Using for…of loop

The for…of loop iterates over the iterable objects (like Array, Map, Set, arguments object, …, etc), invoking a custom iteration hook with statements to be executed for the value of each distinct property.

Syntax:

for ( variable of iterableObjectName) {
...
}

Example: In this example, we will iterate over the elements of an array using the for…of loop and count the number of occurrences of all the elements of the array and print them in the console.

JavaScript
const arr = [
    'geeks', 2, 'geeks', 2, 'Javascript', 4,
    'Javascript', 5, 'for', 6, 'Javascript', 1,
    'for', 5, 7, 8, 'for'
];

const count = {};

for (let ele of arr) {
    if (count[ele]) {
        count[ele] += 1;
    } else {
        count[ele] = 1;
    }
}

console.log(count);

Output
{
  '1': 1,
  '2': 2,
  '4': 1,
  '5': 2,
  '6': 1,
  '7': 1,
  '8': 1,
  geeks: 2,
  Javascript: 3,
  for: 3
}

Approach 5: Using Lodash _.frequencies() Method

In this approach, we are using the _.frequencies() method for calculating the occurance of all elements in the given array.

Example: In this example we are using Lodash library for solving this problem.

JavaScript
// Defining underscore lodash variable 
let _ = require('lodash-contrib');

// Array 
let array = ["Geeks", "Geeks", "GFG",
    "Computer_Science_Portal",
    "Geeks", "GFG"];

let obj = _.frequencies(array);

// Printing object 
console.log("Original Array : ", array);
console.log("Frequency of elements : ", obj);

Output:

Original Array : [“Geeks”, “Geeks”, “GFG”, “Computer_Science_Portal”, “Geeks”, “GFG”]
Frequency of elements : Object {Computer_Science_Portal: 1, GFG: 2, Geeks: 3}

Approach 6: Using ES6 Map

ES6 introduced the Map object that allows you to store key-value pairs. You can leverage this data structure to efficiently count the occurrences of elements in an array.

To count occurrences using `Array.prototype.forEach()`, initialize an empty object or Map, iterate through the array with `forEach()`, and increment the count for each item in the object or Map. This method directly updates the count during iteration.

Example:

JavaScript
const arr = [
    'geeks', 2, 'geeks', 2, 'Javascript', 4,
    'Javascript', 5, 'for', 6, 'Javascript', 1,
    'for', 5, 7, 8, 'for'
];

const countOccurrences = (arr) => {
    const counter = new Map();
    arr.forEach((ele) => {
        counter.set(ele, counter.has(ele) ? counter.get(ele) + 1 : 1);
    });
    return counter;
};

console.log(countOccurrences(arr));

Output
Map(10) {
  'geeks' => 2,
  2 => 2,
  'Javascript' => 3,
  4 => 1,
  5 => 2,
  'for' => 3,
  6 => 1,
  1 => 1,
  7 => 1,
  8 => 1
}

Approach 7: Using JavaScript Objects with the in Operator

In this approach, we use a JavaScript object to keep track of the occurrences of each element in the array. By using the in operator, we can check if the property already exists in the object, allowing us to update the count accordingly.

Example: Here, we will iterate over the elements of an array using a traditional for loop and use the in operator to check and update the count of each element in an object.

JavaScript
let arr = [
    'geeks', 2, 'geeks', 2, 'Javascript', 4,
    'Javascript', 5, 'for', 6, 'Javascript', 1,
    'for', 5, 7, 8, 'for'
];

const countOccurrences = (arr) => {
    const counter = {};
    for (let i = 0; i < arr.length; i++) {
        let ele = arr[i];
        if (ele in counter) {
            counter[ele] += 1;
        } else {
            counter[ele] = 1;
        }
    }
    return counter;
};

console.log(countOccurrences(arr));

Output
{
  '1': 1,
  '2': 2,
  '4': 1,
  '5': 2,
  '6': 1,
  '7': 1,
  '8': 1,
  geeks: 2,
  Javascript: 3,
  for: 3
}

Approach 8: Using Array.prototype.reduce() with a Map

Another approach to count the occurrences of all items in an array is by using the Array.prototype.reduce() method along with a Map object. The reduce() method will iterate over the array and update the Map object to store the count of each element.

Example: In this example, we will use the reduce() method to iterate over the elements of an array, updating a Map object to keep track of the count of each element.

JavaScript
const array = [1, 3, 4, 3, 4, 1, 3, 3, 3, 4];

const countOccurrences = (arr) => {
    return arr.reduce((map, item) => {
        if (map.has(item)) {
            map.set(item, map.get(item) + 1);
        } else {
            map.set(item, 1);
        }
        return map;
    }, new Map());
};

const occurrencesMap = countOccurrences(array);
const occurrencesObj = Object.fromEntries(occurrencesMap);

console.log(occurrencesObj);

Output
{ '1': 2, '3': 5, '4': 3 }





Reffered: https://www.geeksforgeeks.org


JavaScript

Related
How does Backbone.js relate to &quot;traditional&quot; MVC ? How does Backbone.js relate to &quot;traditional&quot; MVC ?
NuxtJS NuxtJS
JavaScript String at() Method JavaScript String at() Method
How to check for &quot;undefined&quot; value in JavaScript ? How to check for &quot;undefined&quot; value in JavaScript ?
Implement polyfill for Promise.all() method in JavaScript Implement polyfill for Promise.all() method in JavaScript

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
11