Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding a specific character in an array

So let's say I have an array that looks like this:

weather = ["sun", "clouds", "rain", "hail", "snow"]

And I want to find and display all of the strings which have the letter "s" in them. This is what I think I should do...

for(var i = 0; i < weather.length; i++)
{
    if(weather[i].indexOf('s') != -1)
    {
        alert(weather);
    }
}

But that just displays all of the weather strings as many times as there are strings with the letter "s" in them. (It will just alert: "sun, clouds, rain, hail, snow" 3 times)

How do I get it to alert just the specific names of the weather which contain the letter "s"?

like image 460
isolatedhowl Avatar asked Oct 23 '25 10:10

isolatedhowl


2 Answers

You need to do alert(weather[i]) instead of alert(weather)

Check this fiddle

like image 167
karthikr Avatar answered Oct 25 '25 22:10

karthikr


as simple modern solution without vars or loops:

alert(
  ["sun", "clouds", "rain", "hail", "snow"].filter(/./.test, /i/)
)
like image 20
dandavis Avatar answered Oct 25 '25 23:10

dandavis