본문 바로가기
JS

자주쓰이는 lodash-es 배열 문법 17가지

by memory-log 2024. 1. 1.

여기에는 lodash-es에서 자주 사용되는 배열 관련 함수의 예시 20개가 포함되어 있습니다. 이 함수들은 배열 조작, 변환 및 필터링에 유용합니다.

 

1. 배열에서 중복 제거:

import _ from 'lodash-es';

const uniqueNumbers = _.uniq([1, 2, 2, 3, 4, 4, 5]);
console.log(uniqueNumbers); // [1, 2, 3, 4, 5]

2. 배열을 문자열로 변환:

import _ from 'lodash-es';

const arrayToString = _.join(['apple', 'orange', 'banana'], ', ');
console.log(arrayToString); // 'apple, orange, banana'

3. 배열에서 특정 값의 인덱스 찾기:

import _ from 'lodash-es';

const index = _.indexOf([1, 2, 3, 4, 5], 3);
console.log(index); // 2

4. 배열을 역순으로 정렬:

import _ from 'lodash-es';

const reversedArray = _.reverse([1, 2, 3, 4, 5]);
console.log(reversedArray); // [5, 4, 3, 2, 1]

5. 배열에서 특정 값의 유무 확인:

import _ from 'lodash-es';

const includesValue = _.includes([1, 2, 3, 4, 5], 3);
console.log(includesValue); // true

6. 배열을 일정 간격으로 나누기:

import _ from 'lodash-es';

const chunkedArray = _.chunk([1, 2, 3, 4, 5], 2);
console.log(chunkedArray); // [[1, 2], [3, 4], [5]]

7. 배열에서 특정 값 제외하기:

import _ from 'lodash-es';

const withoutValue = _.without([1, 2, 3, 4, 5], 3);
console.log(withoutValue); // [1, 2, 4, 5]

8. 배열에서 무작위 요소 추출:

import _ from 'lodash-es';

const randomElement = _.sample([1, 2, 3, 4, 5]);
console.log(randomElement); // 무작위로 선택된 요소

9. 배열에서 일부 요소 추출:

import _ from 'lodash-es';

const slicedArray = _.slice([1, 2, 3, 4, 5], 1, 4);
console.log(slicedArray); // [2, 3, 4]

10. 배열 요소를 특정 값으로 채우기:

import _ from 'lodash-es';

const filledArray = _.fill(Array(5), 'Hello');
console.log(filledArray); // ['Hello', 'Hello', 'Hello', 'Hello', 'Hello']

11. 배열을 정렬된 상태로 유지하며 새 요소 추가:

import _ from 'lodash-es';

const sortedInsert = _.sortedUniq([...sortedArray, newValue]);
console.log(sortedInsert); // 정렬된 상태로 유지되는 배열

12. 배열 요소를 무작위로 섞기:

import _ from 'lodash-es';

const shuffledArray = _.shuffle([1, 2, 3, 4, 5]);
console.log(shuffledArray); // 무작위로 섞인 배열

13. 배열을 평탄화하기:

import _ from 'lodash-es';

const flattenedArray = _.flattenDeep([1, [2, [3, [4]], 5]]);
console.log(flattenedArray); // [1, 2, 3, 4, 5]

14. 배열 요소를 특정 기준으로 그룹화:

import _ from 'lodash-es';

const groupedByType = _.groupBy(['apple', 'banana', 'orange', 'grape'], fruit => fruit.length);
console.log(groupedByType);
// { '5': ['apple', 'grape'],
//   '6': ['banana', 'orange'] }

15. 배열을 특정 길이로 채우고 반복:

import _ from 'lodash-es';

const repeatedArray = _.times(3, () => 'Hello');
console.log(repeatedArray); // ['Hello', 'Hello', 'Hello']

16. 배열에서 가장 작은/큰 요소 찾기:

import _ from 'lodash-es';

const minNumber = _.min([1, 2, 3, 4, 5]);
const maxNumber = _.max([1, 2, 3, 4, 5]);
console.log(minNumber, maxNumber); // 1, 5

17. 배열 요소를 특정 값으로 매핑:

import _ from 'lodash-es';

const mappedArray = _.map([1, 2, 3, 4, 5], num => num

댓글