이 번역은 완료되지 않았습니다. 이 문서를 번역해 주세요.
This is an experimental technology
Check the Browser compatibility table carefully before using this in production.
flat() 메서드는 모든 하위 배열 엘리먼트를 지정된 깊이까지 재귀적으로 이어붙여 새로운 배열을 생성합니다.
{{EmbedInteractiveExample("pages/js/array-flatten.html")}}
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
구문
arr.flat([depth]);
매개변수
depthOptional- 중첩된 배열 구조를 평평하게 만들기 위한 깊이 값. 기본값은 1.
반환 값
하위 배열을 이어붙인 새로운 배열.
예제
중첩 배열 펼치기
var arr1 = [1, 2, [3, 4]]; arr1.flat(); // [1, 2, 3, 4] var arr2 = [1, 2, [3, 4, [5, 6]]]; arr2.flat(); // [1, 2, 3, 4, [5, 6]] var arr3 = [1, 2, [3, 4, [5, 6]]]; arr3.flat(2); // [1, 2, 3, 4, 5, 6]
배열 구멍 제거
flat 메소드는 배열의 빈 슬롯을 제거합니다.
var arr4 = [1, 2, , 4, 5]; arr4.flat(); // [1, 2, 4, 5]
대안
reduce와 concat
var arr1 = [1, 2, [3, 4]]; arr1.flat(); //단일 레벨 배열로 평평하게 하려면 arr1.reduce((acc, val) => acc.concat(val), []);// [1, 2, 3, 4]
//reduce와 concat을 사용해 재귀적으로 깊은 레벨 평평화(deep level flatten)를 가능하게 하려면
var arr1 = [1,2,3,[1,2,3,4, [2,3,4]]];
function flattenDeep(arr1) {
return arr1.reduce((acc, val) => Array.isArray(val) ? acc.concat(flattenDeep(val)) : acc.concat(val), []);
}
flattenDeep(arr1);// [1, 2, 3, 1, 2, 3, 4, 2, 3, 4]
//스택을 사용해 재귀 없는 평평화
var arr1 = [1,2,3,[1,2,3,4, [2,3,4]]];
function flatten(input) {
const stack = [...input];
const res = [];
while (stack.length) {
// 스택에서 값을 pop
const next = stack.pop();
if (Array.isArray(next)) {
// 배열 항목을 다시 push, 원래 인풋을 수정하지 않음
stack.push(...next);
} else {
res.push(next);
}
}
//입력 순서를 복구하기 위한 reverse
return res.reverse();
}
flatten(arr1);// [1, 2, 3, 1, 2, 3, 4, 2, 3, 4]
명세
| Specification | Status | Comment |
|---|---|---|
Array.prototype.flat proposal |
Finished (4) |
브라우저 호환성
The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.
Update compatibility data on GitHub
| Desktop | Mobile | Server | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Basic support | Chrome Full support 69 | Edge No support No | Firefox Full support 62 | IE No support No | Opera Full support 56 | Safari Full support 12 | WebView Android Full support 69 | Chrome Android Full support 69 | Edge Mobile No support No | Firefox Android Full support 62 | Opera Android Full support 56 | Safari iOS Full support 12 | Samsung Internet Android No support No | nodejs Full support 11.0.0 |
Legend
- Full support
- Full support
- No support
- No support