0

I'm a newbie to Javascript please help me to solve my problem

function myFunction() {
var fr = ["banana", "orange", "apple", "mango"];
var n = fr.length;
var s = "a";
for(i=0;i<n;i++){
  if(fr[i].indexOf(s) != -1){
     console.log(fr[i]);          
  }
 }        
}

and the output im getting is

banana
orange
apple
mango

but what i want is that it should print only the word that starts with the given letter/word

i.e., : apple 
pankaj
  • 33
  • 2
  • 7

4 Answers4

2

When you are checking index!=-1, that is basically you are checking that a is present anywhere in string.

If you want to check that string start with a you should check if a is at 0th index.

Check this in if condition

if(fr[i].indexOf(s) === 0)

This will give the expected output.

Mritunjay
  • 25,338
  • 7
  • 55
  • 68
  • perfect ! thank you so much friend :) you saved my life,i have been trying to solve this problem since 2 days. – pankaj Aug 29 '14 at 14:15
  • This solution will be slow if `fr[i]` is pretty long. FYI, the better way is http://stackoverflow.com/a/4579228/961314. – Heejin Aug 29 '14 at 14:17
0

The reason that all of them are showing is because all of those strings contain the character 'a'. If you only want to show the strings that begin the the character 'a' Mritunjay's solution is the way to go

QuinnFTW
  • 554
  • 5
  • 12
0

You can use substring. This example will give you the first letter in the string.

 if(fr[i].indexOf(s) != -1){
     if(fr[i].substring(1, 0) === "b")
     {
         console.log("b found");
     }
 }
patricmj
  • 365
  • 2
  • 3
  • 18
0

(For the record) Case insensitive filtering of your array on /^a/i (see MDN)

["banana", "orange", "apple", "mango"]
  .filter( function (v) { return v[0].toLowerCase() === 'a'; } );
KooiInc
  • 119,216
  • 31
  • 141
  • 177