Jquery filter array of object with loop
Asked Answered
H

3

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 ?

Herby answered 23/6, 2015 at 9:5 Comment(0)
R
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;
});
Rorke answered 23/6, 2015 at 9:11 Comment(1)
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.Herby
M
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;
    });
});
Mink answered 23/6, 2015 at 9:8 Comment(2)
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()Incandescent
@Incandescent 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.Mink
T
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;
    }
Transceiver answered 23/6, 2015 at 9:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.