directory
- Stack the way
- Reduce + recursively
- Traverse the way
First, the way of stack
While + (original data: concat stacks, post POP + push if item is array) + (otherwise: unshift), get the final flattened array
/ / the stack
function flat(arr) {
const result = [];
const stack = [].concat(arr); // Copy the array elements onto the stack. Assignment directly changes the original array
// If the stack is not empty, the loop is iterated
while(stack.length ! = =0) {
const val = stack.pop(); // The tail pops up
if (Array.isArray(val)) { stack.push(... val);// If the array is pushed again, and expanded one layer, and pushed in from the tail
} else {
result.unshift(val); // If it is not an array, insert it into the result array.
// Insert from the header, the first insert is actually the last result.
// The last one inserted into the header is actually the first. That's it. The tail is still in the tail, the head is still in the head.}}return result;
}
const arr = [1.2.3[4[5]],6]
flat(arr);// [1, 2, 3, 4, 5, 6]
Copy the code
Reduce mode + recursion
Recursive concat can pave one-level arrays
function flat(arr){
return arr.reduce((pre, cur) = > pre.concat(Array.isArray(cur) ? flat(cur) : cur), [])
};
const arr = [1.2.3[4[5]],6]
flat(arr);// [1, 2, 3, 4, 5, 6]
Copy the code
3. Traversal mode map or forEach
function flat1(arr){
let res = [];
arr.map((item,index) = >{ // arr. ForEach works as well
if(Array.isArray(item)){
res = res.concat(flat1(item));// The return value of concat is the combined array. Concat does not change the raw data
}else{
res.push(item); // Push returns the length of the array. Push changes the raw data.}})return res;
}
const arr = [1.2.3[4[5]],6]
flat1(arr)
// [1, 2, 3, 4, 5, 6]
Copy the code
conclusion
- Stack mode:
while
+(Raw data: concat stack, pop + push if item is array)
+(Otherwise: Result array unshift)
.You get the array that's finally paved out
- The return value of concat is the combined array. Concat does not change the raw data
- The return value of push is the length of the array, which is generally useless. Push changes the raw data.