Flat And FlatMap  in Javascript

Flat And FlatMap in Javascript

·

1 min read

  1. flat method It returns a new flattened array .

For Example Rightwards arrow const array=[ 1, 2, [ 3, 4, ] , 5, [ 6, 7 ] ] ; console.log( array.flat( ) )

image.png OUTPUT
[ 1, 2, 3, 4, 5, 6, 7 ]

We Got a brief About Flat method . Lets Explore With An Example

const users=[ { name:"Dev", money:[ 23, 67, 87, -45 ], }, { name:"Rahul", money:[ 20, 74, 100, -20 ], }, ]

In above I have an array of Users where I have 2 users with their name and money ( +ive number→saving , -ve number → spending )

Now I wanted a single array containing both of their money

const moneyArr=users.map( ( user ) =>{

return user.money; }) console.log( moneyArr )

image.png

output [ [ 23, 67, 87, -45 ], [ 20, 74, 100, -20 ] ] Now I need to Flat this array moneyArr.flat() image.png output [ 23, 67, 87, -45, 20, 74, 100, -20 ]

  1. flatMap Now I can apply flat and map both method simultaneously Using flatMap Method

const moneyArr=users.flatMap((user)=>{ return user.money; }) console.log(moneyArr)

image.png output will be same [ 23, 67, 87, -45, 20, 74, 100, -20 ]

For More Such Blogs You can follow me here and On twitter : twitter.com/gulatidev66