Last active
April 4, 2023 18:51
-
-
Save sridharrajs/3d2753d2f11d98942c0b4a40781f69bf to your computer and use it in GitHub Desktop.
Use flatMap instead of filter + map
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const ipl2023Auction = [ | |
{ name: "Dhoni", broughtBy: 'CSK' }, | |
{ name: "Santner", broughtBy: 'CSK' }, | |
{ name: "Faf", broughtBy: 'RCB' }, | |
{ name: "Kohli", broughtBy: 'RCB' }, | |
{ name: "Rohit", broughtBy: 'MI' }, | |
{ name: "Archer", broughtBy: 'MI' } | |
]; | |
ipl2023Auction.filter(player => player.broughtBy === 'MI').map(player => player.name) // [ 'Rohit', 'Archer' ] | |
const CSK = ipl2023Auction.flatMap((player) => | |
player.broughtBy === "CSK" ? [player.name] : [] | |
); | |
console.log(CSK); // [ 'Dhoni', 'Santner' ] | |
// using reduce() | |
const cskByReduce = ipl2023Auction.reduce((acc, player) => { | |
if (player.broughtBy === "CSK") { | |
acc.push(player.name); | |
} | |
return acc; | |
}, []); | |
console.log(cskByReduce); // [ 'Dhoni', 'Santner' ] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment