0
[["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
1
  • Iterate through the array(s) and check whether the entry startsWith or contains "AA"? Commented Jul 17, 2017 at 6:31

2 Answers 2

1

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

but may be tomorrow index can get change
In that case we have to iterate through each element in the array, which won't be a problem.
which won't be a problem - prove it
@RomanPerekhrest Just make it a function and extract the argument, it's really not a lot of magic.
1

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))
answered Jul 17, 2017 at 6:35

2 Comments

but may be tomorrow index can get change
I have added which will increase the running time but if the index change it will not be affected.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.