7

I have an array of objects like this:

myArray = [
{label: "a", 
value: "100"},
{label: "b",
value: "101"},
{label: "c",
value: "102"}
...

I want to filter it like this:

myArrayFiltered = myArray.filter(function(v){ 
    return v["value"] == "101" || v["value"] == "102"});

Which will return

myArrayFiltered = [
{label: "b",
value: "101"},
{label: "c",
value: "102"}]

in this example but I want to do the filter with an array of values. How can I do that ?

GtAntoine
  • 1,049
  • 1
  • 8
  • 12

3 Answers3

5

Just check if the value you're filtering on is in your array

myArrayFiltered = myArray.filter(function(v){ 
    return ["102", "103"].indexOf(v.value) > -1;
});
Andrei Nemes
  • 3,062
  • 1
  • 16
  • 22
  • This one works. Don't forget to add ); at the end. In fact I wasn't using an array to filter but an array of objects like the first array. I converted it in an array to get only the values and then use this solution. – GtAntoine Jun 23 '15 at 09:38
0

You could use the .some method inside your filter:

var requiredValues = ["101", "102", "103"];
myArrayFiltered = myArray.filter(function(v){ 
    return requiredValues.some(function(value) {
        return value === v.value;
    });
});
CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176
  • You can pass `requiredValues` as the second parameter into `.filter(callback[, thisArg])` and then use `this.indexOf()`. Then you won't have to rely on a "global" parameter - [Array.prototype.filter()](https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) – Andreas Jun 23 '15 at 09:17
  • @Andreas Certainly possible. I prefer this approach, as it feels unnatural to pass in a variable and pass it off as *context*, so I'll leave this as-is. – CodingIntrigue Jun 23 '15 at 09:20
0
var arrValues = ["101", "102"];



 var result = getData(arrValues,"102")



 function getData(src, filter) {
        var result = jQuery.grep(src, function (a) { return a == filter; });
        return result;
    }
Kamalesh
  • 21
  • 3