Count Occurrences of each Element in Array in JavaScript-Code Examples

Radu TM

Count Occurrences of each Element in Array in JavaScript

JavaScript by Radu TM β€’ June 21, 2022

const arr = ['🍎', '🍌', '🍊', '🍎', '🍎', '🍊', '🍌', '🍍'];

// create a map to store the counts of each element
const counts = new Map();

// iterate over the array
for (const element of arr) {
  // if the element is not in the map, set its count to 1
  if (!counts.has(element)) {
    counts.set(element, 1);
  }
  // otherwise, increment its count
  else {
    const count = counts.get(element);
    counts.set(element, count + 1);
  }
}

// print the counts
for (const [element, count] of counts) {
  console.log(`${element} occurs ${count} time(s)`);
}

0

26.440

Count Occurrences of each Element in Array in JavaScript

JavaScript by Radu TM β€’ June 21, 2022

const arr = [ '🍎', 'πŸ‹', 'πŸ‡', '🍊', '🍎', 'πŸ‹' ];

// create an empty object to store counts
const counts = {};

// loop over the array
for (const elem of arr) {
  // if an element is not yet a key in the counts object, set it to 1
  if (!counts[elem]) {
    counts[elem] = 1;
  // otherwise, increment its count
  } else {
    counts[elem] += 1;
  }
}

// log the counts object
console.log(counts);

/*
The console will log:
{
  '🍎': 2,
  'πŸ‹': 2,
  'πŸ‡': 1,
  '🍊': 1
}
*/

0

26.440

Related JavaScript Queries

Latest JavaScript Queries

Explore code examples by categories