Flatten / Unlatten

wooo·2023년 5월 7일
0

Flatten

자바스크립트에서 flatten은 array 구조 안에 또 다른 array를 인덱스로 가질 때, array를 평평하게 만드는 작업을 뜻한다. 이때 array의 메서드인 flat()함수를 사용하며, 모든 하위 배열 요소를 지정한 깊이까지 재귀적으로 이어붙인 새로운 배열을 생성한다.

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]

Unflatten

unflatten은 flatten과 반대로 flat된 객체나 배열을 다시 깊이 있게 바꿔주는 것이다.

const { flatten, unflatten } = require("arr-flatten-unflatten");

let flat = flatten([2, 4, [8, [2, [32, 64]], 7], 5]);
/**
 * => {
 * "[0]": 2,
 * "[1]": 4,
 * "[2][0]": 8,
 * "[2][1][0]": 2,
 * "[2][1][1][0]": 32,
 * "[2][1][1][1]": 64,
 * "[2][2]": 7,
 * "[3]": 5
 * }
 * */

unflatten(flat);
// => [2, 4, [8, [2, [32, 64]], 7], 5]

출처

0개의 댓글