Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find all the elements in javaScript array that start with certain letter

Is there any way to do this filtering out only items in an array that start with the letter a. ie

var fruit = 'apple, orange, apricot'.split(',');
  fruit = $.grep(fruit, function(item, index) {
  return item.indexOf('^a'); 
  });
alert(fruit);
like image 225
user2678132 Avatar asked Oct 25 '25 04:10

user2678132


2 Answers

Three things:

  • You want to split by ', ', not ','
  • indexOf doesn't take a regex, but a string, so your code searches for a literal ^. Use search if you want to use regular expressions.
  • indexOf (and search) do return the index where they find the sought-after term. You'll have to compare that to your expectation: == 0. Alternatively, you can use the regex test method which returns a boolean.

alert('apple, orange, apricot'.split(', ').filter(function(item, index) {
    return item.indexOf('a') == 0; 
}));
alert('apple, orange, apricot'.split(', ').filter(function(item, index) {
    return /^a/.test(item); 
}));
like image 161
Bergi Avatar answered Oct 26 '25 16:10

Bergi


You have to trim the spaces from the item before checking.

Regex to check if start with: ^a

var fruit = 'apple, orange, apricot'.split(',');
fruit = $.grep(fruit, function (item, index) {
    return item.trim().match(/^a/);
});
alert(fruit);

Other solution:

var fruits = [];
$.each(fruit, function (i, v) {
    if (v.match(/^a/)) {
        fruits.push(v);
    }
});
alert(fruits);
like image 41
Tushar Avatar answered Oct 26 '25 17:10

Tushar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!