반응형
1. 최신 자바스크립트 API인 flat() 사용
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat
Array.prototype.flat() - JavaScript | MDN
The flat() method of Array instances creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.
developer.mozilla.org
2. 직접 메소드 작성해보기
// arr: 배열, d: 차원
const flatDeep = (arr: any[], d = 1): any[] => {
return d > 0
? arr.reduce((acc, val) => {
return acc.concat(
Array.isArray(val) ? flatDeep(val, d - 1) : val
) as any[];
}, [])
: arr.slice();
};
반응형
'웹_프론트엔드 > JavaScript' 카테고리의 다른 글
[자바스크립트] 객체 불변성(Immutability)이 중요한 이유 (0) | 2024.05.11 |
---|---|
[자바스크립트] 이미지 URL을 File 또는 FileList로 변환하기 (0) | 2023.11.10 |
[JS] 클로저란? (0) | 2023.07.25 |
[JS] 스코프(Scope)란? (0) | 2023.07.24 |
[JS] 연속된 정수 배열을 만드는 다양한 방법 (0) | 2023.07.14 |