[["Django UnChainers","AA-24010"],["General","AA-26191"]]
I have one array in above form. I want to retrieve all the value with prefix AA (which are in the second position). Is there any way where I can fetch the value by passing prefix?.
I know the way where I can get the value by passing index but may be tomorrow index can get change so is it possible to fetch the value by passing prefix?
Aravindh Gopi
2,17630 silver badges36 bronze badges
asked Jul 17, 2017 at 6:30
2 Answers 2
In case OP wants a function to do this.
function(arr, pattern){
return arr.map(function(x){
return x.filter( word => ~ word.indexOf(pattern))
});
}
var arr =
[ [ "Django UnChainers", "AA-24010" ], [ "General", "AA-26191" ]];
var list = arr.map(function(x){
if(~(x[1].indexOf('AA'))){
return x[1];
}
});
console.log(list);
In case the index changes in future, iterate through each string and check for the "AA" string. Check the below code.
var arr =
[ [ "Django UnChainers", "AA-24010" ], [ "General", "AA-26191" ]];
var list = arr.map(function(x){
return x.filter( word => ~ word.indexOf('AA'))
});
console.log(list);
answered Jul 17, 2017 at 6:34
4 Comments
RomanPerekhrest
but may be tomorrow index can get change
Hassan Imam
In that case we have to iterate through each element in the array, which won't be a problem.
RomanPerekhrest
which won't be a problem - prove it
Yoshi
@RomanPerekhrest Just make it a function and extract the argument, it's really not a lot of magic.
this is shorter
var = [nested array]
a.filter(x => x[1].startsWith('AA'))
//in case you are not sure about the index
a.filter(x => x.filter(y => y.startsWith('AA').length > 0))
2 Comments
RomanPerekhrest
but may be tomorrow index can get change
Hamuel
I have added which will increase the running time but if the index change it will not be affected.
lang-js
startsWith
orcontains
"AA"
?