반응형

flatMap() 메서드

flatMap() 메서드는 먼저 매핑함수를 사용해 각 엘리먼트에 대해 map() 메서드를 수행 후, 결과를 새로운 배열로 평탄화해줍니다. 이는 깊이 1의 flat()이 뒤따르는 map()과 동일하지만, flatMap()은 아주 유용하며 둘을 하나의 메소드로 병합할 때 조금 더 효율적입니다.

 

구문

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

 

매개변수

  • callback: 새로운 배열의 엘리먼트를 생성하는 함수입니다. 3개의 인자를 받습니다.
  • index: 배열에서 처리되고 있는 현재 엘리먼트의 인덱스입니다.
  • array: map()이 호출된 배열입니다.
  • thisArg: callback실행에서 this로 사용할 값입니다.

 

반환 값

각 엘리먼트가 callback함수의 결과이고, 깊이 1로 평탄화된 새로운 배열입니다.

 

예제

map()과 flatMap()

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

console.log(arr.map(x => [x * 2])); // [[2], [4], [6], [8]]

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

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

 

단어의 리스트를 생성합니다.

let arr1 = ["it's Sunny in", "", "California"];

console.log(arr1.map(x => x.split(" "))); // [["it's","Sunny","in"],[""],["California"]]

console.log(arr1.flatMap(x => x.split(" "))); // ["it's","Sunny","in","California"]

 

reduce + concat vs flatMap

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

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

console.log(arr1.reduce((acc, x) => acc.concat([x * 2]), [])); // [2, 4, 6, 8]

 

반응형

+ Recent posts