how to use the countby function from lodash in javascript

The countBy function from lodash creates an object composed of keys generated from the results of running each element through an iteratee function. The corresponding value of each key is the number of times the key was generated from the iteratee function. Here's how to use it:

index.tsx
// First, install lodash: 
npm install lodash

// Then, import countBy and use it on an array or object:
const _ = require('lodash');

// Example 1: count how many times each letter appears in a string
const str = 'hello world';
const lettersCount = _.countBy(str);
console.log(lettersCount); // { h: 1, e: 1, l: 3, o: 2, ' ': 1, w: 1, r: 1, d: 1 }

// Example 2: count how many fruits of each type in an array of fruits
const fruits = ['apple', 'banana', 'orange', 'apple', 'banana', 'banana'];
const fruitsCount = _.countBy(fruits);
console.log(fruitsCount); // { apple: 2, banana: 3, orange: 1 }

// Example 3: count how many people have each age in an array of objects
const people = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
  { name: 'Charlie', age: 25 },
  { name: 'David', age: 30 },
  { name: 'Eve', age: 25 },
];
const ageCount = _.countBy(people, 'age');
console.log(ageCount); // { '25': 3, '30': 2 }
931 chars
27 lines

In the first example, countBy counts how many times each letter appears in the string "hello world". The resulting object has keys for each letter and values for how many times each letter appears in the string.

In the second example, countBy counts how many times each fruit appears in the array fruits. The resulting object has keys for each fruit and values for how many times each fruit appears in the array.

In the third example, countBy counts how many times each age appears in the array of people objects. The resulting object has keys for each age and values for how many times each age appears in the array of objects.

gistlibby LogSnag