flatten, unflatten
- 자바스크립트에서는 flatten은 중첩된 배열구조를 하나의 배열로 만드는 것을 의미한다.
unflatten
- unflatten은 중첩된 배열 구조를 의미한다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const arr = [1 , 2, [3, 4]] |
└ 위와 같은 배열안에 배열이 중첩되어 있는 구조를 unflatten이라고 생각하면 된다.
flatten
- flatten은 중첩 배열을 평탄화 하는 것을 의미한다.
※ 평탄화 ?
→ 중첩 배열을 하나의 배열로 만드는 것을 의미한다.
flatten의 방법
Array.prototype.flat()
- 자바스크립트에는 flat이라는 메서드가 존재한다.
- flat 메서드는 모든 하위 배열 요소를 지정한 깊이까지 재귀적으로 이어붙여 새로운 배열을 생성한다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 arr3 = [1, 2, [3, 4, [5, 6, [7, 8]]]] | |
arr.flat(Infinity) // [1, 2, 3, 4, 5, 6, 7, 8] |
└ 사용할 때 평탄화 할 깊이를 지정해 주어야 한다. (default 값은 1 / infinity : 모든 중첩배열을 평탄화)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const arr5 = [1, 2, , 4, 5]; | |
arr5.flat(); | |
// [1, 2, 4, 5] |
└ flat 메서드는 배열안의 비어있는 부분도 제거해준다.
flat의 대안
reduce와 concat
- reduce 메서드와 concat 메서드를 사용하면 flat과 같은 효과를 적용할 수 있다.
- 하지만, 이 방법은 배열의 깊이 값을 조절 할 수 없다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const arr = [1, 2, [3, 4]]; | |
arr.flat(); // [1, 2, 3, 4] | |
arr.reduce((acc, val) => acc.concat(val), []); / [1, 2, 3, 4] | |
const flattened = arr => [].concat(...arr); |
reduce, concat, isArray 재귀
- 배열의 깊이 값의 제한이 없다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const arr = [1, 2, [3, 4, [5, 6]]]; | |
function flatDeep(arr, d = 1) { | |
return d > 0 | |
? arr.reduce( | |
(acc, val) => | |
acc.concat(Array.isArray(val) ? flatDeep(val, d - 1) : val), | |
[] | |
) | |
: arr.slice(); | |
} | |
flatDeep(arr, Infinity); // [1, 2, 3, 4, 5, 6] |
'React > 2022-上' 카테고리의 다른 글
token, XSS, CSRF (0) | 2022.04.24 |
---|---|
Callback (0) | 2022.04.24 |
Recursive Functions (0) | 2022.04.24 |
React Currying (0) | 2022.04.18 |
React HOC vs HOF (0) | 2022.04.18 |