코드리뷰 하면서 또 하나를 배웠다.
정리를 해보겠다!
언니가 추천해준 아티클을 참조하였습니당
Array.flat()은 느리다?
const arr = [1, 2, [3, 4]];
const flatArr = arr.flat();
// [1, 2, 3, 4]
const deepArr = [1, 2, [3, 4, [5, 6]]];
const flatDeepArr = deepArr.flat(2);
// [1, 2, 3, 4, 5, 6]
const veryDeepArr = [1, [2, [3, [4, [5]]]]];
const completelyFlatArr = veryDeepArr.flat(Infinity);
// [1, 2, 3, 4, 5]
const arrWithEmpty = [1, 2, , 4, 5];
const cleanedArr = arrWithEmpty.flat();
// [1, 2, 4, 5]
flat()
의 특성이 문제가 될 수 있음재귀함수 사용
function customFlat(arr, depth = 1) {
let result = [];
arr.forEach(item => {
if (Array.isArray(item) && depth > 0) {
result = result.concat(customFlat(item, depth - 1));
} else {
result.push(item);
}
});
return result;
}
const arr = [1, [2, [3, [4, [5]]]];
console.log(customFlat(arr, Infinity));
// [1, 2, 3, 4, 5]
라이브러리 사용
lodash
의 _.flattenDeep()
함수는 깊이에 상관없이 배열을 평탄화_.flattenDepth()
지정된 깊이만큼 배열을 평탄화const _ = require('lodash');
const arr = [1, [2, [3, [4, [5]]]];
console.log(_.flattenDeep(arr));
// [1, 2, 3, 4, 5]