I have an array of arrays , and I need to filter by position 0 of the elements.
I need to filter multiple values extracted from another array, so OR operator is not my way because the amount of values I have is not fixed.
var arr = [
["202",27,44],
["202",194,35],
["200",233,344],
["190",333,444],
];
var newArr = arr.filter(function(item){
//fixed amount of values, not working for my purpose
return item[0] === "190" || item = "200"
});
I need something like
var newArr = arr.filter(function(item){
return item[0] === filterValues
//where filterValues = ["190","200",etc]
});
function in this case should return :
[["200",233,344],["190",333,444]]
This question uses underscorejs but im new to javascript so it was hard to me to apply it to my problem.
And this is for Angularjs.
I hope you can give me a hand.
P.S : Sorry about my english, its not my native language.
regards
You can use indexOf()
on an array to find if the array contains a value. It will be -1
if not present, otherwise it will be the index in the array of the first instance of the value, i.e. >=0
So, for example:
arr.filter(function(item){return ["190","200"].indexOf(item[0])>=0})
As per your comment, the filters keys are embedded inside nested arrays. You can extract these using map()
, e.g.
var keys = [["190",222],["200",344]].map(function(inner){return inner[0]});
A function implementing this (thanks to @Shomz for the bulk of the code) would look like:
var arr = [
["202",27,44],
["202",194,35],
["200",233,344],
["190",333,444],
];
function myFilter(query) {
return arr.filter(function(item){
return query.indexOf(item[0]) >= 0;
})
}
var q = [["190",222],["200",344]];
var keys = q.map(function(inner){
return inner[0];
});
alert(myFilter(keys));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With