Skip to content

Commit f26fab5

Browse files
committed
tech(array): flatMap method by example
1 parent 58b6b06 commit f26fab5

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

array/flatMap.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
//Understanding Array.prototype.flatMap()
2+
// myArray.map().flat(1) - equivalent
3+
4+
let movies = [
5+
'Dog Soldiers',
6+
['In Bruges', 'From Paris with Love', 'Layer Cake'],
7+
'The Big Lebowski',
8+
'',
9+
' ',
10+
'Memento, The Platform,Fight Club, ',
11+
'Hotel Rwanda, Moon, Under the Skin',
12+
'Lady Bird',
13+
['Platoon', 'Wall-E'],
14+
]
15+
let arr = movies.flatMap((entry) => {
16+
if (Array.isArray(entry)) {
17+
return entry
18+
} else if (typeof entry === 'string' && entry.trim() === '') {
19+
return [] //remove the empty strings
20+
} else {
21+
//other strings
22+
return entry
23+
.split(',')
24+
.map((txt) => txt.trim())
25+
.filter((txt) => txt != '')
26+
}
27+
})
28+
console.log(arr)
29+
30+
let strings = ["one","two","three"]
31+
let numbers = [1,2,3]
32+
33+
//let mappedStringNumber = numbers.map((val, idx) => [val, strings[idx]]) //[ [ 1, 'one' ], [ 2, 'two' ], [ 3, 'three' ] ]
34+
let mappedStringNumber = numbers.flatMap((val, idx) => [val, strings[idx]]) //[ 1, 'one', 2, 'two', 3, 'three' ]
35+
console.log(mappedStringNumber)
36+
37+

0 commit comments

Comments
 (0)