DEV Community

Discussion on: filter, map and reduce in JS. When and Where to use??

Collapse
 
captainyossarian profile image
yossarian • Edited

You will get noticeable performance hit if your array has more than 1K elements. In worst case scenario you will iterate 2 times over 1K elements. Btw, what makes you think that reducer is not readable?

type User = {
  name: string;
  city: string;
  birthYear: number;
}
declare const users: User[]

const currentYear = new Date().getFullYear();

const olderThan25 = (user: User) =>
  user.birthYear && (currentYear - user.birthYear) > 25 ? [user] : []

const getName = ({ name }: User) => name

const userNames = users.reduce((acc, user) =>
  olderThan25(user)
    ? acc.concat(getName(user))
    : acc,
  [] as Array<User['name']>
);
Enter fullscreen mode Exit fullscreen mode

You can chain map and filter in functional languages, like for example F# because there is no intermediate value.

Collapse
 
nehal_mahida profile image
Nehal Mahida

That's a good point with a great code presentation. 👍🏻