Saurabh Garg
Saurabh Garg

Reputation: 201

How to retrieve the value from an array without index

[["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?

Upvotes: 0

Views: 1016

Answers (2)

Hamuel
Hamuel

Reputation: 633

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))

Upvotes: 1

Hassan Imam
Hassan Imam

Reputation: 22534

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);

Upvotes: 1

Related Questions