본문 바로가기
Programming/JavaScript

자바스크립트 JavaScript flatMap() 함수

by 혀코 2019. 3. 11.

flatMap() 함수는 map() 함수와 비교해서 이해하는 것이 좋습니다.

우선 map() 함수를 살펴보자면, 안의 함수를 실행하여 나온 결과값들을 각각의 Array로 묶어 하나의 Array를 반환합니다.


const alphabets = ["a","b","c"];
const fruits = ["apple", "banana", "cherry"];

const mappedExample = alphabets.map((alphabets,index) => [alphabets, fruits[index]]);
console.log(mappedExample);

// [["a","apple"],["b","banana"],["c","cherry"]]

그래서 단 하나의 Array를 만들기 위해서 flatMap() 함수를 사용합니다.


const alphabets = ["a","b","c"];
const fruits = ["apple", "banana", "cherry"];

const mappedExample = alphabets.flatMap((alphabets,index) => [alphabets, fruits[index]]);
console.log(mappedExample);

// ["a","apple","b","banana","c","cherry"]

결과적으로 flatMap() 함수는 map() 함수의 값에 다시 flat() 함수를 적용한 값과 동일한 역할을 수행합니다.

댓글