count frequency of each element
in an array
[ for-loop | Object ]

Count frequency of each element

Write a function that takes an array and returns an object with each unique element of the array as the key and the number of times each element appears in the array, as the value


Example ...

Enter an array ...

[2, 3, 6, 2, 4, 6, 2, 2, 4, 6] original array

Returns an object with each unique element of the array as the key

and the number of times each element appears in the array as the value

{"2": 4, "3": 1, "4": 2, "6": 3} object

Each key is a string.

Frequency of elements found.

"2" found 4 times

"3" found 1 time

"4" found 2 times

"6" found 3 times

Arrays are used to store multiple values in a single variable.

Each value is called an element, and each element has a numeric position in the array, known as its index.

Arrays are zero-indexed, meaning the first element is at index 0, the second at index 1, and so on.

Arrays can contain any data type, including numbers, strings, and objects.

const arr1 = [2, 4, 6]; array

arr1[0]; element at index 0 → 2

arr1[1]; element at index 1 → 4

arr1[2]; element at index 2 → 6

arr1[3]; element at index 3 → undefined index not found


Objects are a data structure used to store related data collections.

It stores data as key/value pairs, where each key is a unique identifier for the associated value.

Each key must be a string and must be unique, each value can be any data type.

If you define an object with duplicate keys, the last one will overwrite any preceding ones.

Find the value for any given key in the object.

const obj1 = {"A": 4, "B": 5, "C": 6 }; object

obj1["A"]; key "A"4

obj1["B"]; key "B"5

obj1["C"]; key "C"6

obj1["D"]; key "D"undefined key not found

Find the value for any given key in the object.

const obj2 = {"A": 4, "B": 5, "C": 6 }; object

const str = "ABC"; string

obj2[str[0]];4

obj2[str[1]];5

obj2[str[2]];6

obj2[str[3]];undefined key not found


Strings are a sequence of zero or more characters written inside quotes used to represent text.

Strings may consist of letters, numbers, symbols, words, or sentences.

Strings are immutable, they cannot be changed.

Each character in a string has an index.

The first character will be index 0 the second character will be index 1 and so on.

There are two ways to access an individual character in a string.

charAt() method

const str1 = "abc"; string

str1.charAt(0); character at index 0 → "a"

str1.charAt(1); character at index 1 → "b"

str1.charAt(2); character at index 2 → "c"

str1.charAt(3); character at index 3 → "" index not found

Alternatively use at() or slice() methods

bracket notation []

const str2 = "abc"; string

str2[0]; character at index 0 → "a"

str2[1]; character at index 1 → "b"

str2[2]; character at index 2 → "c"

str2[3]; character at index 3 → undefined index not found


Numbers are used to represent both integer and floating-point values.

Numbers are most commonly expressed in literal forms like 255 or 3.14159 ↴

let num1 = 5; → number

let num2 = 2.5; → number

let num3 = num1 + num2;

console.log(num3); returns ↴

7.5 → number


Count frequency of each element in an array using a for loop


for loop repeatedly executes a block of code until a specified condition evaluates to false.

The loop runs a block of code a set number of times, defined by an initialization, a condition, and an increment.

const arr = []; → empty array

for (let x = 0; x < 4; x++) {

arr.push(x);

}

console.log(arr);

Initialize an empty array arr

Loop variable x is initialized to 0

Condition x < 4 is checked before each iteration.

The loop will continue to run as long as x is less than 4

The loop repeatedly executes a block of code 4 times, from 0 to 3

For each iteration of the loop, the current value of x is pushed to the end of the array.

After each iteration, x is incremented by 1 x++

When x reaches 4 the condition evaluates to false, terminating the loop.

[0, 1, 2, 3] → array returned


Initialize an array to count frequency of each element.

const array1 = ["A", "C", "B", "A", "D", "A", "B", "C", "B", "A"]; → user input


Define a function frequency to count the frequency of each element in the array.

function frequency(arr) {}

The function takes an array as input arr and returns an object representing the frequency of each element. The original array remains unchanged.

The keys represent the unique elements from the array.

The values denote the number of times each element appears.

Initialize an empty object to hold the frequency counts.

const freq = {} freq

Loop through each element in arr

for (let x = 0; x < arr.length; x++) {}

Check if the current element [arr[x]] already exists as a key in the freq object.

if (freq[arr[x]])

If the element is already a key in the object → increment the count by 1

freq[arr[x]] += 1 freq[arr[x]] = freq[arr[x]] + 1

else if the element is NOT found in the object, add it to the object.

freq[arr[x]] = 1 → initialize the key with a value of 1

The function returns the freq object, which contains the frequency of each element.

return freq

keys represent the unique elements in the array.

values denote the number of times each element appears.

["a", "b", "a", "c", "b", "a"] → array

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

"a" found 3 times

"b" found 2 times

"c" found 1 time


Call the function with ↴

frequency(array1);


Count frequency of each element in array.

const array1 = ["A", "C", "B", "A", "D", "A", "B", "C", "B", "A"];

function frequency(arr) {

const freq = {};

for (let x = 0; x < arr.length; x++) {

if (freq[arr[x]]) {

freq[arr[x]] += 1;

} else {

freq[arr[x]] = 1;

}

}

return freq;

}

call function

frequency(array1); returns ↴

{A: 4, C: 2, B: 3, D: 1}


Number elements are treated as string elements

[1, 1, 1, "1", "1"] returns ↴

{1: 5}


Alternative using a ternary operator ↴

const array2 = ["A", "C", "B", "A", "D", "A", "B", "C", "B", "A"];

function frequency(arr) {

const freq = {};

for (let x = 0; x < arr.length; x++) {

freq[arr[x]] ? freq[arr[x]]++ : (freq[arr[x]] = 1);

}

return freq;

}

call function

frequency(array2); returns ↴

{A: 4, C: 2, B: 3, D: 1}


Alternative ↴

freq[arr[x]] += 1; same as ↴

freq[arr[x]]++;

Count frequency of each element