This is the 27th day of my participation in the August More Text Challenge.

  • Flattening an array is simply converting an array of nested layers (nesting can be any number of layers) into an array of only one layer. As a simple example, assume that a function called flatten can flatten an array, as shown in the following code.
var arr = [1[2[3.4.5]]];
console.log(flatten(arr)); // [1, 2, 3, 4,5]
Copy the code

In fact, it “flatten” the multidimensional array and output the last one-dimensional array. Now that you know what it looks like, let’s try writing a flatten function. There are several ways to do this.

Method 1: ordinary recursive real

The common recursive idea is easy to understand, is through the loop recursion way, one by one to traverse, if each item is still an array, then continue to traverse, the use of recursive procedures, to achieve the array of each item of the connection. Let’s look at how this method is implemented, as shown below.

1 / / method
var a = [1[2[3.4.5]]];
function flatten(arr) {
  let result = [];

  for(let i = 0; i < arr.length; i++) {
    if(Array.isArray(arr[i])) {
      result = result.concat(flatten(arr[i]));
    } else{ result.push(arr[i]); }}return result;
}
flatten(a);  // [1, 2, 3, 4,5]
Copy the code

This code can be seen from above, and finally the result returned is the result of a flat, this code is the core in the process of iterating over recursive operations, is found in the process of traversing the array element or an array of time for recursive operations, the results of an array with array concat method of joining together to finally to return to the result of an array, The final output is a flattened array.

Method 2: Use reduce function to iterate

As can be seen from the above common recursive function, in fact, it is to process each item of the array and reduce to realize array splicing, thus simplifying the code of the first method. The transformed code is shown as follows.

var arr = [1[2[3.4]]];
function flatten(arr) {
    return arr.reduce(function(prev, next){
        return prev.concat(Array.isArray(next) ? flatten(next) : next)
    }, [])
}
console.log(flatten(arr));// [1, 2, 3, 4,5]
Copy the code

After this code is executed on the console, the desired result can also be obtained. Here you can recall the parameter problem of Reduce. We can see that the first parameter of Reduce is used to return the final sum. The idea is the same as the first recursive method, but the code is much simpler by using Reduce, and the flattening problem is also solved.

Let’s look at the next implementation.

This method is implemented by using the extension operator and some methods, both of which are used to achieve the purpose of flattening the array, or take a look at the code.

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

As can be seen from the execution result, we first filter out the items that are still group numbers in the array by using some method of the array, then perform concat operation, concatenate them into the original array by using ES6 expansion operator, and finally return the original array, achieving the expected effect.

The first three ways to achieve array flattening are actually the most basic ideas, are derived from the most common recursive ideas, especially the first two implementation methods are relatively similar. It is worth noting that reduce method can be implemented in many application scenarios. Because several parameters provided by reduce method are flexible and can solve many problems, it is worth using and mastering it.

Is there another way to do this? Please read on.

Method 4: split and toString processing together

We can also use the split and toString methods together to flatout arrays. Since arrays carry a toString method by default, we can convert arrays directly to comma-separated strings, and then use the split method to convert strings back to arrays, as shown in the following code.

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

These two methods convert multidimensional arrays directly into comma-concatenated strings and then repartition them into arrays, which you can execute on the console to see the result.

Method 5: Call flat in ES6

We can also directly call the flat method in ES6, we can directly implement the array flattening. Let’s look at the syntax of the flat method:

arr.flat([depth])

Depth is the parameter flat. Depth is the expansion depth of the array that can be passed (the default is left blank and the value is 1). So what happens if you have multiple layers? The parameter can also be passed into Infinity, meaning that no matter how many layers are expanded. So let’s see how we can do that using flat. Look at the code below.

5 / / method
var arr = [1[2[3.4]]];
function flatten(arr) {
  return arr.flat(Infinity);
}
console.log(flatten(arr)); // [1, 2, 3, 4,5]
Copy the code

As you can see, an array with two layers nested has achieved the desired effect by setting the flat method parameter to Infinity. You can also set it to 2 to achieve the same effect.