What is array flattening?

It’s essentially converting a multidimensional array into a one-dimensional array.

[1, 2, three, four, five, [June]]] = >,2,3,4,5,6,7,8 [1]

Six ways to flatten an array

  • Flat method in ES6 (recommended)

Call the flat method in ES6 directly

arr.flat([depth])

Depth means how deep to expand. The default is 1, and Infinity is passed in.

const testArray = [1[2[3[4[5[6[7[[[[[[8['ha']]]]]]]]]]]]]].const resultArray = testArray.flat(Infinity);
console.log(resultArray); // [ 1, 2, 3, 4, 5, 6, 7, 8, 'ha'] 
Copy the code

Recommend this, the simplest, behind need not see!! 😂

Let’s say you’re in an interview and the interviewer says, “Can we implement the flat method?” 😰 Uh… forgot

To avoid GG, look at this: Implement flat

To be honest, you’re not going to be able to implement the flat method after you have the flat method. So the back of these understand on the line, not recommended use.

  • Recursive calls

Concat merges arrays recursively

const testArray = [1[2[3[4[5[6[7[[[[[[8['ha']]]]]]]]]]]]]].function flatten(arr) {
  let result = [];
  arr.forEach((item) = >{
    if (Array.isArray(item)) {
      // Call the array recursively
      result = result.concat(flatten(item));
    } else {
      // Not array pushresult.push(item); }})return result; 
}

const result = flatten(testArray);
console.log(result); // [ 1, 2, 3, 4, 5, 6, 7, 8, 'ha'] 
Copy the code
  • reduce

Reduce

For those of you who don’t understand Reduce, look at this example

[0.1.2.3.5].reduce(function(accumulator, currentValue, currentIndex, array){
  return accumulator + currentValue;
});
// Result is 11
Copy the code
The callback accumulator currentValue currentIndex array
All parameter values are called for the first time 0 1 1 [0, 1, 2, 3, 5]
All parameter values are called the second time 1 2 2 [0, 1, 2, 3, 5]
Call all parameter values for the third time 3 3 3 [0, 1, 2, 3, 5]
Call all parameter values for the fourth time 6 5 4 [0, 1, 2, 3, 5]

reference

Reduce to achieve flattening, in fact, also used recursive method, but reduce can realize traversal, and can quickly process parameters and return, the code is more concise than the previous method

const testArray = [1[2[3[4[5[6[7[[[[[[8['ha']]]]]]]]]]]]]].function flatten(arr) {
  return arr.reduce((prev, curv) = > {
    return prev.concat(Array.isArray(curv) ? flatten(curv) : curv); } []); }const result = flatten(testArray);
console.log(result); // [ 1, 2, 3, 4, 5, 6, 7, 8, 'ha'] 
Copy the code
  • Extend operator implementation

Some knowledge points:

The logic is: when an array has an element in it, the array is deconstructed (using the extension operator), and each loop reduces the (penultimate) outer [] until there are no more arrays in the array. The code is also very simple!

Example: the console. The log (… [1, 2, 3)); / / output 1, 2, 3

function flatten(arr) {
  while (arr.some(item= > (Array.isArray(item)))) { arr = [].concat(... arr); }return arr;
}
const result = flatten(testArray);
console.log(result); // [ 1, 2, 3, 4, 5, 6, 7, 8, 'ha'] 
Copy the code
  • Re matching (just look, not recommended)

The logic is to convert the string to a regular match, strip out all [], and add a [] in the outermost layer.

var arr = [1[2[3.4]]];
function flatten(arr) {
  let str = JSON.stringify(arr);
  str = str.replace(/(\[|\])/g.' ');
  str = '[' + str + '] ';
  return JSON.parse(str); 
}
console.log(flatten(arr)); // [1, 2, 3, 4]
Copy the code
  • ToString split (check it out, not recommended)

The number type becomes a string, so this isn’t really flat

var arr = [1[2[3.4]]];
function flatten(arr) {
    return arr.toString().split(', ');
}
console.log(flatten(arr)); // ["1", "2", "3", "4"]

Copy the code

conclusion

Assuming that flat processing is needed in the real scene, just flat(Infinity) is good, and other things are just messing around 😂😂

MDN, JavaScript core principles – if away