3

I have an array

var months = ["January", "February", "March", "April", \
    "May", "June", "July", "August", "September", "October", \
    "November", "December"];

I have strings like "Nov", "October", "Jun", "June", "Sept", "Sep" etc. The point is, the string can be a substring of one of the months.

What is the best way to compare the string to be a substring of the array elements? How do I find out the index of the month?

I am looking at javascript/jQuery.

I know I can just loop through the array checking against each element using search and break when found. I want something better.

9
  • It's not too difficult to do manually. What have you tried? Commented Dec 24, 2012 at 18:51
  • You can use Array#forEach but ultimately you'll need to loop through the array. Commented Dec 24, 2012 at 18:53
  • I need the index also, so Array#some won't work. Commented Dec 24, 2012 at 18:55
  • @JanDvorak Array#forEach returns a modified array. Commented Dec 24, 2012 at 18:56
  • 2
    What's wrong with iterating over each item in the array and making the comparison? What do you mean by "better"? Shorter code? More efficient? Commented Dec 24, 2012 at 18:56

3 Answers 3

5
var month_index = function(target) {
        target = target.toLocaleLowerCase();
        return jQuery.inArray(true, jQuery.map(months, function(s) {
            return s.toLocaleLowerCase().indexOf(target) > -1;
        }))
    };

var index_of_october = month_index("oct");
Sign up to request clarification or add additional context in comments.

3 Comments

@flem: indexOf looks for a substring and returns the index if found, -1 if not. Also, updated it to be locale-sensitive and case-insensitive.
What is the output of this?
@ATOzTOA: index_of_october is 9. Try it out in Firebug's console.
2
var  substr = 'nov', months = ["december", "november", "feb"];

var index = months.indexOf( months.filter(function(v){ return v.indexOf(substr) >= 0;})[0]);
alert(index)

http://jsfiddle.net/KeMe9/

Comments

0

Put your array items in lower case

var txt = "Sep";
var found = false;
txt = txt.toLowerCase();
  for (var i = 0; i < 12; i++) {
    if (months[i].indexOf(txt) > -1) {
        found = true;
        break;
  }
}

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.