add after ary assign assignIn assignInWith assignWith at before bind bindAll bindKey camelCase capitalize castArray ceil chain chunk clamp clone cloneDeep cloneDeepWith cloneWith compact concat conformsTo countBy create curry curryRight debounce deburr defaults defaultsDeep defer delay difference divide drop dropRight each eachRight endsWith entries entriesIn eq escape every extend extendWith fill filter find findIndex findKey findLast findLastIndex findLastKey first flatMap flatMapDeep flatMapDepth flatten flattenDeep flattenDepth flip floor forEach forEachRight forIn forInRight forOwn forOwnRight fromPairs functions functionsIn get groupBy gt gte has hasIn head inRange includes indexOf initial intersection invert invertBy invoke invokeMap isArguments isArray isArrayBuffer isArrayLike isArrayLikeObject isBoolean isBuffer isDate isElement isEmpty isEqual isEqualWith isError isFinite isFunction isInteger isLength isMap isMatch isMatchWith isNaN isNative isNil isNull isNumber isObject isObjectLike isPlainObject isRegExp isSafeInteger isSet isString isSymbol isTypedArray isUndefined isWeakMap isWeakSet join kebabCase keyBy keys keysIn last lastIndexOf lowerCase lowerFirst lt lte map mapKeys mapValues max maxBy mean meanBy memoize merge mergeWith min minBy multiply negate nth omit omitBy once orderBy overArgs pad padEnd padStart parseInt partial partialRight partition pick pickBy pull pullAll pullAllBy pullAllWith pullAt random rearg reduce reduceRight reject remove repeat replace rest result reverse round sample sampleSize set setWith shuffle size slice snakeCase some sortBy sortedIndex sortedIndexOf sortedLastIndex sortedLastIndexOf sortedUniq split spread startCase startsWith subtract sum sumBy tail take takeRight tap template throttle thru toArray toFinite toInteger toLength toLower toNumber toPairs toPairsIn toPlainObject toSafeInteger toString toUpper transform trim trimEnd trimStart truncate unary unescape union uniq uniqBy uniqWith unset unzip unzipWith update updateWith upperCase upperFirst values valuesIn without words wrap wrapperAt wrapperChain wrapperCommit wrapperFlatMap wrapperLodash wrapperNext wrapperPlant wrapperReverse wrapperToIterator wrapperValue xor zip zipObject zipObjectDeep zipWith

Lodash _.countBy

Overview

The lodash _.countBy method is a powerful utility that helps you count the number of occurrences of values in a collection or an array in JavaScript. It returns an object where the keys are the values in the collection, and the values are the number of occurrences of that value in the collection.

This method takes two parameters: the collection to iterate over and a function that maps each element to its key. The function is optional, and if none is provided, _.identity is used as the default mapping function.

The _.countBy method works by iterating over each element in the collection, applying the mapping function to each, and using the result as the key for the output object. If the key already exists in the output object, the corresponding value is incremented; otherwise, it is initialized to 1.

The following is an example of how to use the method:

const _ = require('lodash');

const pets = ['dog', 'cat', 'bird', 'dog', 'cat'];

const petCount = _.countBy(pets);

console.log(petCount);

// Output: { dog: 2, cat: 2, bird: 1 }

In this example, the _.countBy method is used to count the number of occurrences of each pet in the array. The resulting object shows that there are two dogs, two cats, and one bird in the array.

Another example:

const _ = require('lodash');

const users = [
  { name: 'John', role: 'admin' },
  { name: 'Jane', role: 'user' },
  { name: 'Adam', role: 'admin' },
  { name: 'Eva', role: 'user' },
  { name: 'Mike', role: 'user' },
  { name: 'Susan', role: 'admin' },
];

const roleCount = _.countBy(users, 'role');

console.log(roleCount);

// Output: { admin: 3, user: 3 }

In this example, the _.countBy method is used to count the number of occurrences of each role in the array of users. The resulting object shows that there are three admins and three users in the array.

In conclusion, the _.countBy method is an essential utility that makes it easy to count the number of occurrences of values in a collection or an array in JavaScript. It can be used in a variety of scenarios where counting is required, such as data analysis, reporting, and more.