How to group an array of objects by key

后端 未结 24 3009
后悔当初
后悔当初 2020-11-21 05:13

Does anyone know of a (lodash if possible too) way to group an array of objects by an object key then create a new array of objects based on the grouping? For example, I hav

24条回答
  •  眼角桃花
    2020-11-21 05:42

    Here is a solution inspired from Collectors.groupingBy() in Java:

    function groupingBy(list, keyMapper) {
      return list.reduce((accummalatorMap, currentValue) => {
        const key = keyMapper(currentValue);
        if(!accummalatorMap.has(key)) {
          accummalatorMap.set(key, [currentValue]);
        } else {
          accummalatorMap.set(key, accummalatorMap.get(key).push(currentValue));
        }
        return accummalatorMap;
      }, new Map());
    }

    This will give a Map object.

    // Usage
    
    const carMakers = groupingBy(cars, car => car.make);

提交回复
热议问题