DEV Community

Discussion on: Useful JS functions you aren't using: Array.filter

Collapse
 
aeiche profile image
Aaron Eiche

This is a really excellent point Andrew, and something I totally missed while I was writing it. Thank you for the information and examples!

Collapse
 
vidup profile image
Victor Dupuy

For the record, it's also possible by spreading the object, although it won't work everywhere at the moment, depending on your ES version:

students
  .map(s => ({...s, age: s.age + 1}))
  .filter(s => s.age < 12)
  .forEach(s => console.log(s))
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
tjinauyeung profile image
Tjin

Clean it even more by extracting callbacks

const addYearToAge = person => ({...person, age: person.age + 1})
const isUnderTwelve = person => person.age < 12

students
  .map(addYearToAge)
  .filter(isUnderTwelve)
  .forEach(console.log)
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
vidup profile image
Victor Dupuy

It's beautiful :O