Passing an array to JavaScript filter function

Viewed 138

Let's say I have an array of objects like this:

someObj: [
    {
        name: "Obj1",
        type: "a"
    },
    {
        name: "Obj2",
        type: "b"
    },
    {
        name: "Obj3",
        type: "c"
    }
]       

Now I have a function that should return an array of objects from the someObj array if the parameters passed have the same type property. The thing is the parameter passed is an array and I'm not sure how to make that comparison.

function filter(types) {
  var filtered = someObj.filter(function(item) {

    return item.type == ???

  });       

  return filtered;  
}

filter(["a", "c"]);

How do I compare each item in the array parameter that's passed to item.type so that if they're equal, then the filter function would return to me an array like so:

[
 {
    name: "Obj1",
    type: "a"
 },
 {
    name: "Obj3",
    type: "c"
 }
]
5 Answers

You could search for the type.

ES5 with Array#indexOf

return types.indexOf(item.type) !== -1;

ES6 with Array#includes

return types.includes(item.type);

You can use Array#includes() to check the type:

let someObj = [
    {name: "Obj1",type: "a"},
    {name: "Obj2",type: "b"},
    {name: "Obj3",type: "c"}
]       

function filter(types) {
  return someObj.filter(function(item) {
    return types.includes(item.type)
  }); 
}

console.log(filter(["a", "c"]));

Or a long winded mildly old-fashioned way:

var someObj = [
    {
        name: "Obj1",
        type: "a"
    },
    {
        name: "Obj2",
        type: "b"
    },
    {
        name: "Obj3",
        type: "c"
    }
];


function filter(types) {
  var filtered = someObj.filter(function(item) {
  if ( types.indexOf(item.type) >= 0 )
    {
     return item;
    }

  });       

  return filtered;  
}

var x = filter(["a", "c"]);
console.log(x);

If you can use ES6 syntax you could use the following:

var someObj = [
    {
        name: "Obj1",
        type: "a"
    },
    {
        name: "Obj2",
        type: "b"
    },
    {
        name: "Obj3",
        type: "c"
    }
]

function filter(types){
  return someObj.filter(obj => types.includes(obj.type))
}

console.log(filter(["a", "c"]))

You can use a reduce function here:

function filter(someObj, types) {
    return someObj.reduce((acc, obj) => {
        return types.includes(obj.type)? [...acc, obj] : acc 
    }, [])
}
Related