Got the right answer, but I'm kind of confused - filter()

Hi,

So my code to answer the Use the filter Method to Extract Data from an Array is as follows:

``var numberRating = watchList.map(item => ({

title: item[“Title”],

rating: item[“imdbRating”]

}));

var filteredList = numberRating.filter(item => item.rating > 8)``

Which looks like the second possible solution, but I’m not sure why. Why did I not have to convert the string imbdRating into a number before using filter()?

1 Like

JS must coerce it to a number. It sees that it is trying to compare the left side to a number so it coerces the left side to a number.

console.log('7' > 8);
// false
console.log('9' > 8);
// true
1 Like

Side note - it is recommended to filter before you map/reduce/etc.

2 Likes

It works the other way too, with the string on the right side.

The rules of JS implicit conversion can be tricky and can lead to unexpected results. One of the complaints of JS is that it is fast and loose with data types. I always want to explicitly do the conversion, just to make sure. I would have used the unary + to do it:

item => +item.rating > 8
1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.