'Filter and Include don't work together as expected [closed]
So I have a clients that I'm iterating, then each client has some vehicles as an array represnted in strings, What I want to do is iterate the clients and check if a specific id is included in any of the .vehicles key, but I'm not getting the wanted results, check my function:
const v = clients.clients.filter((c) => {
if (c.vehicles.includes(fields.customer) === true) return c;
});
Solution 1:[1]
You're making it more complicated than needed. You need to return true or false inside filter so:
const v = clients.clients.filter((c) =>
c.vehicles.includes(fields.customer)
);
Then you have a list of clients that have your values. At last your probably use a map to get an array with the desired results.
I'm guessing you want to have all vehicles so the next line is:
let vehicles = v.map(c => c.vehicles)
Solution 2:[2]
An array filter callback should return a boolean, not the item itself
You can try this way
const v = clients.clients.filter((c) => c.vehicles.includes(fields.customer));
Solution 3:[3]
You don't need to put a new if condition in your filter. The filter callback function takes the validation condition directly
const result = words.filter(word => word.length > 6) ;
As you can see above (cf mdn) , the filter method will return a new array with only words that have more than 6 letters.
So, in your case, your function should be only
const v = clients.clients.filter(c => c.vehicles.includes(fields.customer)) ;
Also, I think you need to be careful with the key name, here you have a clients key in an object that has the same name, it's not really understandable, maybe you can have carFleet.clients.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Peterrabbit |
| Solution 3 | Florian Grandjean |
