Skip to content

Instantly share code, notes, and snippets.

@sridharrajs
Last active April 4, 2023 18:51
Show Gist options
  • Save sridharrajs/3d2753d2f11d98942c0b4a40781f69bf to your computer and use it in GitHub Desktop.
Save sridharrajs/3d2753d2f11d98942c0b4a40781f69bf to your computer and use it in GitHub Desktop.
Use flatMap instead of filter + map
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