My map/filter() code not working in FCC

My map/filter() code not working in FCC
0

#1

https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/functional-programming/use-the-filter-method-to-extract-data-from-an-array/
The code works in codepen but not in FCC-

let filteredList = watchList.map(obj => ({rating: Number(obj.imdbRating), title: obj.Title})).filter(rating => {return rating.rating >= 8 });

I’d highly appreciate some guidance.


#2

I thought, rating was a string. Just throwing it out there.


#3

The test is expecting rating to still be a string. Your use of map converted it to a number. Try filtering the array first and then using map to create the smaller object without changing the rating property’s type.

If you think about it, you should probably always implement filter before map, so in case the filtered array is shorter, you are not having to iterate over the full length of the array twice.

An extreme example is if the original array has one million elements, but after the filter is applied, the filtered array only has one element. Running the filter first prevents you from having to iterate over an additional 999, 999 elements.


#4

Thank you both.
Randall, I’ve read you. But let me ask you why the challenge notes that I might have to convert the string to number? That confused me and made me waste time.


#5

It said you might have to convert and not that you have to explicitly have to convert. If you do the filter first and write something like:

watchList.filter(obj => obj.imdbRating >= 8)

You are coercing (“converting” for expression evaluation purposes) the rating to a number when using the >= operator.


#6

Allow me to ask you- What would you have done? Would you have converted it or not?
Besides the fact that you’d have used filter first. Would you have converted the string to number as first approach?


#7

My approach of using filter and map is outlined below in one of my previous replies:

If you think about it, you should probably always implement filter before map, so in case the filtered array is shorter, you are not having to iterate over the full length of the array twice.

You actually do not need to explicitly convert the string to a number no matter which you choose to call first. Each object in the final array must have a rating property which has a string value.