5 JavaScript Ways to Flatten Arrays

5 JavaScript Ways to Flatten Arrays

1. Concept of array flattening

Array flattening is the process of converting a multidimensional array into a one-dimensional array.

[1, [2, 3, [4, 5]]] ------> [1, 2, 3, 4, 5]

2. Implementation

1. reduce

Traverse each item in the array, if the value is an array, traverse recursively, otherwise concat .

function flatten(arr) {  
    return arr.reduce((result, item)=> {
        return result.concat(Array.isArray(item) ? flatten(item) : item);
    }, []);
}

reduce is a method of Array that takes a function as an accumulator and reduces it to a single value for each value in the array (from left to right).
reduce contains two parameters: callback function, the initial value passed to total

// Find the sum of the values ​​in the array: 
arr.reduce((total, item)=> { // total is the previous calculation result, item is the value of each item in the array return total + item;
}, 0);

2. toString & split

Call the toString method of the array to convert the array into a string and then use split to split it back into an array

function flatten(arr) {
    return arr.toString().split(',').map(function(item) {
        return Number(item);
    })
}

Because each item in the array formed after split is a string, a map method is needed to traverse the array and convert each item into a numeric type.

3. join & split

Like toString above, join can also convert an array into a string

function flatten(arr) {
    return arr.join(',').split(',').map(function(item) {
        return parseInt(item);
    })
}

4. Recursion

Recursively traverse each item, if it is an array, continue traversing, otherwise concat

function flatten(arr) {
    var res = [];
    arr.map(item => {
        if(Array.isArray(item)) {
            res = res.concat(flatten(item));
        } else {
            res.push(item);
        }
    });
    return res;
}

5. Spread Operator

es6 's spread operator can convert a two-dimensional array into a one-dimensional array

[].concat(...[1, 2, 3, [4, 5]]); // [1, 2, 3, 4, 5]

Based on this result, we can do a traversal. If arr contains an array, we use the extension operator once until there is no array.

function flatten(arr) {
    while(arr.some(item=>Array.isArray(item))) {
        arr = [].concat(...arr);
    }
    return arr;
}

Summarize:

This concludes this article about 5 JavaScript ways to flatten an array. For more information about how to flatten an array with JavaScript , please search 123WORDPRESS.COM’s previous articles or continue browsing the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • JS array deduplication details
  • Detailed discussion of several methods for deduplicating JavaScript arrays
  • In-depth study of JavaScript array deduplication problem
  • JavaScript array deduplication solution
  • js implements array flattening
  • JavaScript data flattening detailed explanation
  • JavaScript Interview: How to implement array flattening method
  • Introduction to JavaScript array deduplication and flattening functions

<<:  Detailed explanation of the solution to docker-compose being too slow

>>:  A brief discussion on the differences and summary of the three floating point types of float, double and decimal in MySQL

Recommend

Summary of HTML Hack Tags in IE Browser

Copy code The code is as follows: <!--[if !IE]...

Example of how to upload a Docker image to a private repository

The image can be easily pushed directly to the Do...

Detailed explanation of custom configuration of docker official mysql image

In order to save installation time, I used the of...

Solve the conflict between docker and vmware

1. Docker startup problem: Problem Solved: You ne...

js tag syntax usage details

Table of contents 1. Introduction to label statem...

How to use cookies to remember passwords for 7 days on the vue login page

Problem Description In the login page of the proj...

CSS style reset and clear (to make different browsers display the same effect)

In order to make the page display consistent betwe...

Detailed explanation of CSS image splicing technology (sprite image)

CSS image splicing technology 1. Image stitching ...

MySQL Failover Notes: Application-Aware Design Detailed Explanation

1. Introduction As we all know, in the applicatio...

Idea deploys remote Docker and configures the file

1. Modify the Linux server docker configuration f...

How to modify the initial password of a user in mysql5.7

When users install MySQL database for the first t...

CSS and JS to achieve romantic meteor shower animation

1. Rendering 2. Source code HTML < body > &...

MYSQL stored procedures, that is, a summary of common logical knowledge points

Mysql stored procedure 1. Create stored procedure...

Several specific methods of Mysql space cleaning

Table of contents Preface 1. Check the file disk ...