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 _.groupBy

Overview

The lodash _.groupBy method is a utility function that is used for grouping items in a collection based on a specified criterion or property. This method is commonly used in JavaScript applications to create data sets that can be easily analyzed or manipulated.

The _.groupBy method takes two parameters: the collection to be grouped and the criterion for grouping. The criterion can be a property name or a callback function that returns the group key for each item in the collection.

Here is an example usage of the _.groupBy method:

const scores = [
  { score: 70, subject: 'math' },
  { score: 85, subject: 'math' },
  { score: 90, subject: 'science' },
  { score: 80, subject: 'history' }
];

const groupedScores = _.groupBy(scores, 'subject');

console.log(groupedScores);

// Output:
// {
//   'math': [ { score: 70, subject: 'math' }, { score: 85, subject: 'math' } ],
//   'science': [ { score: 90, subject: 'science' } ],
//   'history': [ { score: 80, subject: 'history' } ]
// }

In the example above, an array of scores is grouped by the subject property. The resulting object contains keys for each unique subject, with the corresponding values being arrays of all scores for that subject.

When using a callback function as the criterion, the function should return the group key for each item. Here is an example of grouping by a callback function:

const numbers = [1, 2, 3, 4, 5];
const groupedNumbers = _.groupBy(numbers, (num) => {
  return (num % 2 === 0) ? 'even' : 'odd';
});

console.log(groupedNumbers);

// Output:
// {
//   'odd': [1, 3, 5],
//   'even': [2, 4]
// }

In this example, an array of numbers is grouped by whether they are odd or even, resulting in an object with keys of "odd" or "even", each containing the corresponding numbers from the original array.

Overall, the _.groupBy method is a powerful utility function that provides a simple and efficient way to group items in a collection based on a specified criterion.