Reputation: 2579
I am using this code to filter OUT any parts with categories OTHER than '1', '2', or '3' but the displayed list isn't filtering out cats like 'LG' and 'NHA'. I am using filter incorrectly?
return this.components.filter((c) => {
if (c.cat in ['1', '2', '3']) {
return c;
}
});
Upvotes: 0
Views: 45
Reputation: 26844
filter
's callback function expects a bool return value. You can use includes
to determine whether an array includes a certain element.
If you want to filter components
to only include the elements other than 1,2 and 3, you can use !
to negate the includes
result.
let components = [{cat: '1'}, {cat: '2'}, {cat: '3'}, {cat: '4'},{cat: '5'}];
let result = components.filter((c) => {
return !['1', '2', '3'].includes(c.cat);
});
console.log(result);
Upvotes: 2
Reputation: 1074276
JavaScript's in
operator doesn't check to see if a value is in an array; it checks to see if a property name is present in an object (or its prototypes).
To find out if a value is in an array, you can use the modern includes
(which can be polyfilled on older browsers) method, or the older indexOf
method:
if (['1', '2', '3'].includes(c.cat)) {
or
if (['1', '2', '3'].indexOf(c.cat) != -1) {
For more complex checks, you can use some
which lets you use a callback to check if something matches rather than just doing a value match.
Upvotes: 2