flatten, unflatten

solsolsol·2022년 4월 24일
0

JavaScript

목록 보기
16/17

flatten 과 unflatten

둘의 차이는 깊이가 있냐, 없냐에 달렸다.
flatten은 중첩 배열을 말하고 unflatten 은 평평한, 우리가 일반적으로 떠올리는 배열을 말한다.

.flat()

array 의 메서드로 중첩된 배열을 평탄하게 만들어준다.

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]

0개의 댓글