DEV Community

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

Collapse
 
buntine profile image
Andrew Buntine

Nice work. Just a little note on the last couple of examples. If you want to do this in a functional style, it's important not to mutate state in the map function.

In your last example, the first map actually mutates the original collection with the ++ operator. In order to keep the original collection unchanged you can use the object spread operator in upcoming versions of Javascript, but for now you'll need to do something like this:

students.map((s) => Object.assign({}, s, {age: s.age + 1}))
Enter fullscreen mode Exit fullscreen mode

The second call to map also has the same issue in that it has a side-effect (I/O in this case) that causes the entire expression to return an array of undefined. Obviously there is no way to do I/O without a side-effect and thus the higher-order function you should use here is forEach (which perhaps is the topic of an upcoming blog post?)!

Finally:

students
  .map(s => Object.assign({}, s, {age: s.age + 1}))
  .filter(s => s.age < 12)
  .forEach(s => console.log(s))
Enter fullscreen mode Exit fullscreen mode
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

Collapse
 
xherno profile image
herno

Quick Fix to get this example working:

students
.map(s => Object.assign({}, s, {age: parseInt(s.age, 10) + 1}))
.filter(s => s.age < 12)
.forEach(s => console.log(s));

Age should be parsed as integer, in order to get the addition working, otherwise it will be treated as a string and will result i.e, for age 10, in age: 101

Collapse
 
buntine profile image
Andrew Buntine

Sure, although I'd argue that a better approach would be to represent the age as an integer in the data structure. Especially if the program is planning to perform arithmatic on it! :)