jgravois
jgravois

Reputation: 2579

vue.js: Filtering not working as I expect

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

Answers (2)

Eddie
Eddie

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

T.J. Crowder
T.J. Crowder

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

Related Questions