Posted onEdited onInAlgorithm/算法 Symbols count in article: 991Reading time ≈1 mins.
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
functionflattenArray(arr) { let res = []; for (const item of arr) { if (item instanceofArray) { 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];