How to flatten arrays in JavaScript

Tram Ho

Hello everyone, in this post, I would like to share some knowledge about how to flatten array in javascript . Hope to be of some help to those who are in need of learning. Let’s get started.


Suppose I have the following data returned:

And now the requirement is to get the following result:

So what am I going to do now? The answer is to read through this article to see if there are any good treatment.

1. Use flat () ES6

Flat() will return a new array with the elements of the array in it.

Syntax:

VD1:

Results returned:

So still can not meet the requirements of the beginning of my article. Since our original array has 2 sub arrays, let’s try changing a bit like below:

VD2:

Okay, so it was exactly as I wanted, but with the unknown data how many sub arrays like the above array , it’s hard to handle, right? Don’t worry because ES6 also gave us a parameter that’s Infinity (not under limit):

VD3:

2. Use recursive algorithm

Referring to the recursive algorithm, I myself remember about the first days of computerization in college, surely those who study CNTT are no longer strangers, right. Let’s review a little through the demo below:

Results returned:

Not too difficult, right. Let’s go to another way to see how offline.

3. Use reduce javascript

Reduce can do a lot of things, you can find out at this link . In the scope of this article, I would like to share about how to flatten reduce array .

Results returned:

4. Summary

Above are the shares I have learned, through the above ways, hopefully you can choose the way that you feel suitable for your project.

And if you have another way to do it, please share it below the comment for everyone to see. Thank you everyone for taking a moment to read your comments.

Share the news now

Source : Viblo