stack
stack

Reputation: 10228

How to get array elements which match variable?

I have an array like this:

var numbers = ["one", "two", "three", "four", "five", "six", "seven"];

Now I need to create a new array according to this variable:

var search;

EX1:

var search = 'f';

I want this:

var matches = ['four','five'];

EX2:

var search = 'fi';

I want this:

var matches = ['five'];

EX3:

var search = 'fig';

I want this:

var matches = []; // empty

How can I do that?

Upvotes: 2

Views: 954

Answers (2)

The Process
The Process

Reputation: 5953

you can use concept like this:

var numbers = ["one", "two", "three", "four", "five", "six", "seven"];

var matches = [];

var search = 'f';
var sl=search.length;

for(i=0;i<numbers.length;i++){

  if(numbers[i].substring(0,sl)===search){

       matches.push(numbers[i]);
    }

}

Upvotes: 2

potashin
potashin

Reputation: 44581

You can use filter:

numbers.filter(function(x){ if(x.indexOf(search) >= 0) return x })

JSFiddle

Upvotes: 3

Related Questions