Flatten Array (ลึกลงไป)
รวม Nested Arrays ทุกระดับให้กลายเป็น 1-D Array
1. Array.flat() (ES2019 - แนะนำ)
<script>
const arr = [1, 2, [2, 3, [4, 5, [6, 9]]]];
// Depth 2
console.log(arr.flat(2)); // [1, 2, 2, 3, 4, 5, 6, 9]
// Infinite Depth
console.log(arr.flat(Infinity)); // [1, 2, 2, 3, 4, 5, 6, 9]
</script>
2. concat.apply() (Legacy)
<script>
var arrays = [1, 2, [3, 4, [5, 6]], 9];
var merged = [].concat.apply([], arrays); // 1 Level Only!
console.log(merged); // [1, 2, 3, 4, [5, 6], 9] - Not Deep!
</script>
Warning: concat.apply Flatten แค่ 1 Level เท่านั้น!
3. Recursive Deep Flatten (Custom)
function deepFlatten(arr) {
return arr.reduce((acc, val) =>
Array.isArray(val) ? acc.concat(deepFlatten(val)) : acc.concat(val), []);
}
console.log(deepFlatten([1, [2, [3, [4]]]])); // [1, 2, 3, 4]
4. Generator Function (Memory Efficient)
function* flattenGen(arr) {
for (const item of arr) {
if (Array.isArray(item)) yield* flattenGen(item);
else yield item;
}
}
console.log([...flattenGen([1, [2, [3, [4]]]])]); // [1, 2, 3, 4]
Comparison
| Method | Deep? | Standard | Performance |
|---|---|---|---|
| flat(Infinity) | Yes | ES2019 | Fast (Native) |
| concat.apply | No (1 Level) | ES5 | Fast |
| Recursive Reduce | Yes | Custom | Medium |
| Generator | Yes | Custom | Lazy, Memory Efficient |