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

Detailed explanation of MySQL transactions and MySQL logs

Transactional Characteristics 1. Atomicity: After...

Example code for implementing a hollow mask layer with CSS

Contents of this article: Page hollow mask layer,...

Summary of common tool examples in MySQL (recommended)

Preface This article mainly introduces the releva...

Will the deprecated Docker be replaced by Podman?

The Kubernetes team recently announced that it wi...

js code that associates the button with the enter key

Copy code The code is as follows: <html> &l...

Detailed explanation of the order of JS object traversal

Some of you may have heard that the order of trav...

Complete steps to install Anaconda3 in Ubuntu environment

Table of contents Introduction to Anaconda 1. Dow...

Pure HTML+CSS to achieve typing effect

This article mainly introduces the typing effect ...

Several ways to run Python programs in the Linux background

1. The first method is to use the unhup command d...

Basic use of subqueries in MySQL

Table of contents 1. Subquery definition 2. Subqu...

CnBlogs custom blog style sharing

After spending half the night on it, I finally ma...

How to implement the builder pattern in Javascript

Overview The builder pattern is a relatively simp...

Use vue2+elementui for hover prompts

Vue2+elementui's hover prompts are divided in...

How to configure https for nginx in docker

Websites without https support will gradually be ...