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 ?

3 Answers 3

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;
});
Sign up to request clarification or add additional context in comments.

1 Comment

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.
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;
    });
});

2 Comments

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()
@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.
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;
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.