How to Use Flatten in Node JS Example?

Aug 08, 2022

.

Admin

How to Use Flatten in Node JS Example?

Hi Friends,

Today our leading topic is how to use flatten in node js. We will use flat() in node.js. you can understand the concept of add sub-array contact to arry in node js. if you want to see an example of node js concate to array in sub array, then you are in the right place.

There are many ways to use flatten in node js. I will give you two examples using flat() in node js. The flat() method creates a new array with all sub-array elements concatenated recursively up to the specified depth.

let's see below a simple example with output:

Install Node JS


This step is not required; however, if you have not created the node js app, then you may go ahead and execute the below command:

mkdir my-app

cd my-app

npm init

Example: 1

index.js

//create array list

myArr = [0, 1, 2, [3, 4]];

console.log(myArr.flat());

Output:

[ 0, 1, 2, 3, 4 ]

Example: 2

index.js

//create array list

myArr = [0, 1, 2, [[[3, 4]]]];

console.log(myArr.flat(2));

Output:

[ 0, 1, 2, [ 3, 4 ] ]

I hope it can help you...

#Node JS