Flat Map in javascript is a great technique which you can learn here. Flat map essentially conbines techniques of map and filter Array method into one. I will suggest you to use flatMap() over combination of filter() and map().
FlatMap takes single pass and doesnβt produce intermediate array but filter ()and map() combination produces an intermediate array.
// using filterAndMap
console.time("filterAndMap")
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const squaredOddNumbers = numbers
.filter(num => num % 2 !== 0)
.map(num => num * num)
console.log(squaredOddNumbers); // [1, 9, 25, 49, 81]
console.timeEnd("filterAndMap")
Top comments (0)