Object with the number of elements in the array in JavaScript

Let's have an array:

let arr = ['a', 'b', 'c', 'a', 'a', 'b'];

Let's count how many and what elements there are in this array and present the result as an object like this:

{a: 3, b: 2, c: 1}

To solve this, let's make the object count with the following initial values:

let count = {a: 0, b: 0, c: 0}

We will loop through the array and increase the corresponding value in the object count:

let arr = ['a', 'b', 'c', 'a', 'a', 'b']; let count = {a: 0, b: 0, c: 0}; for (let elem of arr) { count[elem]++; } console.log(count); // shows {a: 3, b: 2, c: 1}

Let's go further: the fact that the object count has characters listed in the initial values, because we usually do not know what elements are in the array.

Let the object count be formed automatically in this way: if there is no such element in count, then it should be assigned the value 1, and if there is, just increase the value by one:

let arr = ['a', 'b', 'c', 'a', 'a', 'b']; let count = {}; for (let elem of arr) { if (count[elem] === undefined) { count[elem] = 1; } else { count[elem]++; } } console.log(count); // shows {a: 3, b: 2, c: 1}

Given a string. Count how many times each of its characters occurs in it.

enru