Array flattening concept

Array flattening refers to reducing the dimension of a multidimensional array to a one-dimensional array:

[1, [2, 3, [4, 5]] ------> [1, 2, 3, 4, 5]Copy the code

Array flattening method

1. Traversal number group + recursion

The basic idea is to iterate through the array, recursively calling the flatten function if there are any arrays in the array, concatenating them and returning the result.

let arr = [1[2.3[4.5]]];
const flatten = (arr) = > {
  let res = [];
  for(const item of arr) {
    if(Array.isArray(item)) {
      res = res.concat(flatten(item));  // Recursively call the flatten function
    } else{ res.push(item); }}return res;
}
console.log(flatten(arr));    // [1, 2, 3, 4, 5]
Copy the code

2. The reduce method

Use reduce to merge and recursively call the flatten function if there are still arrays in the array. Concat concat, return the result.

const flatten = (arr) = > {
  return arr.reduce((res, item) = > {
    return res.concat(Array.isArray(item) ? flatten(item) : item);  
  },[]);
}
console.log(flatten(arr));  //[1, 2, 3, 4, 5]
Copy the code

The Reduce method iterates through all the items in the array and builds a final return value based on that. The method takes two parameters: a merge function (callback function) that is run for each item, and an optional initial value that is the starting point for merge.

// Example: Find the sum of the values of an array
let sum = arr.reduce((prev, cur) = > {  
  return prev + cur;
},0);
Copy the code

3.toString()+split()

Call the array’s toString() method, turn the array into a string and then split it back into an array. The split() method splits the string into arrays based on the delimiter passed in.

const flatten = (arr) = > {
  return arr.toString().split(', ').map(item= > {
    return parseInt(item); })}console.log(flatten(arr));  // [1, 2, 3, 4, 5]
Copy the code

Because each entry in a split array ([“1”, “2”, “3”, “4”, “5”]) is a string, map is used to traverse the array to convert each entry to a numeric type.

4.join()+split()

Like toString() above, join() converts an array to a string.

const flatten = (arr) = > {
  return arr.join(', ').split(', ').map(item= > {
    return parseInt(item); })}console.log(flatten(arr));
Copy the code

5. Expand operators

Extension operators in objects in ES6 (…) Retrieves all traversable properties from the parameter object and copies them to the current object. The argument object is an array, and all the objects in the array are base data types. Copy all the base data types into the new array.

let array = [1.2.3.4];
let copy = [...array];  // The expansion operator can be used to assign an array
console.log(copy);    // [1, 2, 3, 4]

var arr = [1[2.3], [4.5]].letres = [].concat(... arr);// Use the extension operator to turn a two-dimensional array into a one-dimensional array
console.log(res);   // [1, 2, 3, 4, 5]
Copy the code

Based on the above results, if the ARR contains an array, use a single expansion operator, layer by layer, concat join, and return the final result.

function flatten(arr){
  while(arr.some(item= > Array.isArray(item))){ arr = [].concat(... arr);// [1, [2, 3, [4, 5]]
      // [1, 2, 3, [4, 5]]
      // [1, 2, 3, 4, 5]
  }
  return arr;
}
console.log(flatten(arr));    // [1, 2, 3, 4, 5]
Copy the code

See this article for a detailed explanation of the reduce method

Js5 methods to achieve array flattening