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 

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

perfect ! thank you so much friend :) you saved my life,i have been trying to solve this problem since 2 days.
This solution will be slow if fr[i] is pretty long. FYI, the better way is stackoverflow.com/a/4579228/961314.
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

Comments

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

Comments

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

Comments

Your Answer

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.