0%

Some Methods to Flatten a Nested Array

When dealing with data in the client side, programmers often face this data structure that is called nested array. It’s very difficult for us tp iterate through all the data, especially when we wanna compare all of them and get some specific data. Therefore, flattening an array is very important for us to master. This chapter will introduce seversal ways to flatten an array.

Flatten an array in JavaScript

Method 1. Recursion

1
2
3
4
5
6
7
8
9
10
11
12
13
function flattenArray(arr) {
let res = [];

for (const item of arr) {
if (item instanceof Array) {
res = res.concat(flattenArray(item));
} else {
res.push(item);
}
}

return res;
}

Method 2. toString() + split()

1
2
3
4
// FOr example
const arr = [1, 2, [3, 4, 5], [6, [7, 8]], 9];

const newArr = arr.toString().split(",").map(item => parseInt(item));

Method 3. The flat() method

1
2
3
4
// For example
const arr = [1, 2, [3], [4, [5, 6]]];
arr.flat(); // The depth level is 1 by default
arr.flat(2);

Method 4. Recursion + map

1
2
3
4
5
function flattenArray(arr) {
return [].concat(arr.map((item) => {
item instanceof Array ? flattenArray(item) : item
}));
}