Introduction
In this lab, we will learn about the countBy function, which is used to group the elements of an array based on the given function and returns the count of elements in each group. We will explore how this function can be used to map values of an array to a function or property name and how to create an object to count the elements in each group using Array.prototype.reduce(). We will also look at several examples to understand how to use this function in real-world scenarios.
How to Group and Count Elements in an Array Using JavaScript
To group and count elements in an array using JavaScript, follow these steps:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use the
Array.prototype.map()method to map the values of an array to a function or property name. - Use the
Array.prototype.reduce()method to create an object where the keys are produced from the mapped results. - Create a function called
countBythat takes an array and a function as arguments. - Inside the
countByfunction, use a ternary operator to check if the argument passed is a function or a property name. If it's a function, use it as the mapping function. If it's a property name, access that property of the array elements. - Use the
reduce()method to create an object where each key represents a unique element in the array and its value is the number of times it appears in the array.
Here's the code:
const countBy = (arr, fn) =>
arr
.map(typeof fn === "function" ? fn : (val) => val[fn])
.reduce((acc, val) => {
acc[val] = (acc[val] || 0) + 1;
return acc;
}, {});
You can test the countBy function with the following examples:
countBy([6.1, 4.2, 6.3], Math.floor); // {4: 1, 6: 2}
countBy(["one", "two", "three"], "length"); // {3: 2, 5: 1}
countBy([{ count: 5 }, { count: 10 }, { count: 5 }], (x) => x.count); // {5: 2, 10: 1}
Summary
Congratulations! You have completed the Count Grouped Elements lab. You can practice more labs in LabEx to improve your skills.