Reputation: 123
Having a multidimensional array, I would like to filter it, so only the array which has a word ending with underscore '_' is left. I have already accomplished this task using loops.
function searchNames( logins ){
var arr = logins;
var reg = /\w+_\b/;
var newAr = [];
for(var i = 0; i < arr.length; i++) {
for(var x = 0; x < arr[i].length; x++){
if(arr[i][x].match(reg)){
newAr.push(arr[i])
}
}
}
return newAr;
}
Is there any way to do the same using Array.prototype.filter() method. According to MDN reference (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) you can do similar things but I can`t figure out how to filter the arrays inside the array. All of my attempts to use filter method inside of another filter method failed.
Upvotes: 1
Views: 492
Reputation: 1519
Just pass the filter method a useful block:
array = [["hello_","cat"],["dog","dog"]];
arrayTest = function(arr){
resp = false;
arr.forEach(function(str){
if(str.slice(-1) === "_") resp = true;
});
return resp;
}
result = array.filter(arrayTest);
or if you're really married to your regex:
array = [["hello_","cat"],["dog","dog"]];
regex = /\w+_\b/;
arrayTest = function(arr){
resp = false;
arr.forEach(function(str){
if(str.match(regex)) resp = true;
});
return resp;
}
result = array.filter(arrayTest);
Upvotes: 1
Reputation: 382150
You seem to want
var newArr = arr.filter(subArr => subArr.some(e=>/\w+_\b/.test(e)));
Upvotes: 0