When writing the project encountered a multi-level directory tree structure, the need to convert these nested arrays into only one layer of the array to display, so there is a summary of the common methods of the array flattening, in this record.

What is array flattening?

Array flattening refers to converting a multidimensional array into a one-dimensional array, that is, extracting an array with other arrays nested inside it into a one-dimensional array without nesting. Here’s an example:

Var array = [1, 2, 3] var array = [1, 2, 3, 4]Copy the code


How to flatten an array?


Array.prototype.flat()

This is the method provided by ES6 for array flattening. This method returns a new array and does not alter the original array:

letArr1 = [1, 2, 3], 4]. The console log (arr1. Flat ()) / / print [1, 2, 3, 4]Copy the code

Note that flat() defaults to a flat layer nesting:

let[[array = [1, 2, 3], 4]] the console. The log (array) flat ()) / / print [[2, 3] 1, 4]Copy the code

We can take an integer argument to indicate the number of flat layers:

let[[array = [1, 2, 3], 4]] the console. The log (array) flat (2)) / / print [1, 2, 3, 4]Copy the code

If you want to convert an array to a one-dimensional array no matter how many layers are nested, you can use the Infinity keyword as an argument:

let[[array = [1, 2, 3], 4]] the console. The log (array) flat (Infinity)) / / print [1, 2, 3, 4]Copy the code


Using extension operators and concat()

Arrays can be expanded using the extension operator, and arrays can be merged using concat(), but only one level can be expanded:

let array = [1, [[2, 3], 4]] 
function flatten(array) {
    return[].concat(... Array)} console.log(flatten(array)) // Prints [1, [2, 3], 4]Copy the code

To fully expand, you need to iterate over the nested array and expand:

let array = [1, [[2, 3], 4]] 
functionFlatten (array){// Use some() to check whether the elements in the array are an arraywhile(array.some(item => {
        return Object.prototype.toString.call(item) === '[object Array]'})){ array = [].concat(... array); }returnarray; } console.log(flatten(array)); // Print [1, 2, 3, 4]Copy the code


recursive

Define the target empty array, and then we process each item of the original array. If this item is an array, we use concat() to merge the subitem into the target array. If this item is not an array, we push it directly into the target array.

let array = [1, [[2, 3], 4]] 
function flatten(array){
    let res = [];
    array.forEach((item, index, array) => {
        if (Object.prototype.toString.call(item) === '[object Array]'){
            res = res.concat(flatten(item));
        } else {
            res.push(array[index])
        }
    })
    returnres; }; Console. log(flatten(array)) // Prints [1, 2, 3, 4]Copy the code


toString()

When elements are strings or numbers, toString() can convert an array to a string, and then split() can retrieve an array, but this method is limited, so use it discreetically. Here’s an example of an array full of numbers flattened using toString() :

let array = [1, [[2, 3], 4]] 
function flatten(array) {
    return array.toString().split(', ').map(item => +item); } console.log(flatten(array)) // Prints [1, 2, 3, 4]Copy the code


Write in the last

There are many other ways to flatten arrays. You can also use a for loop, but array.prototype.flat () is the most convenient HHH.

Please let me know if there is anything wrong or improper in this article. Thank you


Refer to the link

ECMAScript introduction to 6

JS Array Thematic 1️ diffuse array