JavaScript&TypeScript

JavaScript flat(), flatMap()

hjkang

ES2019에 추가된 flat(), flatMap()에 대해 알아보자.

 

 

flat()

  • 지정한 깊이(기본값 1)까지 하위 배열을 평탄화한 새로운 배열로 생성하여 반환한다.
  • 배열의 구멍도 제거한다.

 

구문

 const newArr = arr.flat([depth])

예제

const arr1 = [1, 2, [3, 4]];
arr1.flat();
// [1, 2, 3, 4]

const arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat();
// [1, 2, 3, 4, [5, 6]]

const arr3 = [1, 2, [3, 4, [5, 6]]];
arr3.flat(2);
// [1, 2, 3, 4, 5, 6]

const arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
arr4.flat(Infinity);
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

const arr5 = [1, 2, , 4, 5];
arr5.flat();
// [1, 2, 4, 5]

 

 

 

flatMap()

  • map을 수행한 후 결과를 새로운 배열로 평탄화한다.

 

구문

arr.flatMap(callback(currentValue[, index[, array]])[, thisArg])

예제

let arr1 = [1, 2, 3, 4];

arr1.flatMap(x => [x * 2]);
// [2, 4, 6, 8]

// 한 레벨만 평탄화됨
arr1.flatMap(x => [[x * 2]]);
// [[2], [4], [6], [8]]

 

 


참고

- https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/flat

- https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap