Hello Guys today i want to show you how to use map method with filter in javascript.
Lets get started...
filter() - This method is used to filter...
For further actions, you may consider blocking this person and/or reporting abuse
Yeah it returned undefined after the output but when using in react i used the JSX inside it so it worked fine there
Please add a warning for newbies to first filter the data and then map it. Mapping data that will be filtered out next is considered bad practice. It results in faster computation.
So filtering and mapping should be done separately not in a chaining ?
That is not what I think Ferry is referring to here. Just the Filter then Map is better than Map then Filter.
Map then Filter is a 2N process. Filter the Map is only a 2N operation in the worse case, otherwise it would be an N+(N-filtered items).
If for some reason you have to Map then Filter it might be better to consider using a Reduce operation to combine the predicate and mapping functions into the reducer function.
Yes that's what I was thinking
Also if you map and then filter, you can get rid of null values with something like
arr.filter(x => x)
, it may depend on the code but still is 2N so you shouldn't worry about itI also used it in my project for searching the dataset and it works fine
Not entirely sure why you'd want to filter an array, then map all the filtered values to
undefined
🤔The filtered values are not undefined they are the values we get after filtering the array with a given condition
It can be used to create a search bar without button event
I used it in my project for filtering the data for the user's using an input HTML tag
I think you misread my comment. I didn't say the filtered values were
undefined
, I said you are mapping the filtered values toundefined
since your function insidemap
isn't returning anything. You seem to be usingmap
incorrectly here -forEach
would be the correct thing to use as @lukeshiru points out.Also, if you are going to
filter
thenmap
- you could also consider doing all of this inside onereduce
- which would be more efficient.I console logged just to see the output but i have used it in react and used the JSX inside the map function which filters the data and then show the remaining data on the screen,It worked fine in react and map() is popular in React for mapping the value to our HTML template without writing the same html again and again for all the values
I'm not sure why you would want to use
map
without manipulating the values? The whole purpose ofmap
is to 'map' one set of values to another set of values using a function.