isolatedhowl
isolatedhowl

Reputation: 191

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"?

Upvotes: 4

Views: 26301

Answers (4)

Upvesh Kumar
Upvesh Kumar

Reputation: 54

very simple

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

      weather.forEach(function(arrayItem,arrayIndex,array){
              if(array[arrayIndex].match('s')){
               alert(array[arrayIndex]);
              }
      })

Explanation:

forEach() method calls a function for each element in the array.
arraytItem like='sun' , 'clouds' etc.
arrayIndex=position of arrayItem;
array=weather;

Upvotes: 1

dandavis
dandavis

Reputation: 16726

as simple modern solution without vars or loops:

alert(
  ["sun", "clouds", "rain", "hail", "snow"].filter(/./.test, /i/)
)

Upvotes: 5

karthikr
karthikr

Reputation: 99620

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

Check this fiddle

Upvotes: 6

isolatedhowl
isolatedhowl

Reputation: 191

Oh. I think I was just missing a small detail.

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

Upvotes: 2

Related Questions