본문 바로가기

JavaScript/Lodash

[Lodash] _.groupBy() 함수 설명 및 사용 예제/예시

반응형

구문(Syntax)

_.groupBy(collection, [iteratee=_.identity])
각 수집 요소를 반복 실행한 결과에서 생성된 키로 구성된 개체를 만듭니다. 그룹화된 값의 순서는 수집에서 발생하는 순서에 따라 결정됩니다. 각 키의 해당 값은 키 생성을 담당하는 요소의 배열입니다. 반복자는 다음(value) 하나의 인수로 호출됩니다.

Creates an object composed of keys generated from the results of running each element of collection thru iteratee. The order of grouped values is determined by the order they occur in collection. The corresponding value of each key is an array of elements responsible for generating the key. The iteratee is invoked with one argument: (value).

매개변수(Arguments)

- collection (Array|Object): 반복할 컬렉션입니다.
- [iteratee=_.identity] (Function): 키를 변환시키는 반복대상입니다.

- collection (Array|Object): The collection to iterate over.
- [iteratee=_.identity] (Function): The iteratee to transform keys.

반환 값(Returns)

(Object): 구성된 집계(aggregate) 객체를 반환합니다.

(Object): Returns the composed aggregate object.

 

예제(Example)

예제 1) 두 번째 인자로 원하는 함수를 추가할 수 있습니다. 

_.groupBy([6.1, 4.2, 6.3], Math.floor);
// [6.1, 4.2, 6.3] 배열을 순회하며, // Math.floor(6.1) = 6 함수를 실행한 결과 값을 키로 새로운 객체를 만들어 반환합니다.
// Math.floor(6.1) = 6
// Math.floor(4.2) = 4
// Math.floor(6.3) = 6
// 반환값: { '4': [4.2], '6': [6.1, 6.3] }

예제 2) 두 번째 인자로 `_.property` 함수의 축약형을 함수 대신 이용할 수  있습니다.

_.groupBy(['one', 'two', 'three'], 'length');
// == _.groupBy(['one', 'two', 'three'], _.property('length'))
// ['one', 'two', 'three'] 배열을 순회하하며 length에 따라 그룹을 만듭니다.
// 반환값:  { '3': ['one', 'two'], '5': ['three'] }

 

 

Reference

 

 

반응형