Introduction
In this lab, we will explore the concept of creating an object with the unique values of an array as keys and their frequencies as the values. We will achieve this by making use of the Array.prototype.reduce() method to map unique values to an object's keys, adding to existing keys every time the same value is encountered. Through this lab, we will gain a deeper understanding of the reduce method and how it can be used to solve programming problems efficiently.
Instructions for Counting Value Frequencies
To count the frequency of values in an array, follow these steps:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use the
Array.prototype.reduce()method to map unique values to an object's keys, adding to existing keys every time the same value is encountered. This will create an object with the unique values of the array as keys and their frequencies as the values. - The code for this operation is as follows:
const frequencies = (arr) =>
arr.reduce((a, v) => {
a[v] = a[v] ? a[v] + 1 : 1;
return a;
}, {});
- To use this function, call
frequencieswith the array as its argument. For example:
frequencies(["a", "b", "a", "c", "a", "a", "b"]); // { a: 4, b: 2, c: 1 }
frequencies([..."ball"]); // { b: 1, a: 1, l: 2 }
With these instructions, you can easily count the frequency of values in any given array.
Summary
Congratulations! You have completed the Value Frequencies lab. You can practice more labs in LabEx to improve your skills.