how to use the countby function from the lodash library in typescript

To use the countBy function from the lodash library in TypeScript, first install the lodash library:

index.ts
npm install lodash
19 chars
2 lines

Then, import the countBy function and use it as follows:

index.ts
import { countBy } from 'lodash';

const items = ['apple', 'banana', 'apple', 'orange', 'banana', 'banana'];

const itemCount = countBy(items, item => item);

console.log(itemCount);
// Output: { apple: 2, banana: 3, orange: 1 }
229 chars
9 lines

In this example, we pass an array of items to the countBy function along with a function that determines how to count each item. The function simply returns the item itself, so countBy will count how many times each item appears in the array.

The resulting object contains each item as a key and the count as a value.

Note that the countBy function can count based on any property or combination of properties of the array items, not just the items themselves.

gistlibby LogSnag