1

Lets say i have the following array:

['1', '1/2', 'fresh', 'tomatoes']

how can i get the index of the first item, that beginns with a letter, in this case "fresh"?

Please note that it should work with every letter, not just with a specific one.

Thanks.

3 Answers3

4

An alternative is using the function findIndex along with a regex to check the first char.

Assuming every string has at least one char.

let arr = ['1', '1/2', 'fresh', 'tomatoes'],
    index = arr.findIndex(s => /[a-z]/i.test(s[0]));
    
console.log(index);
Ele
  • 33,468
  • 7
  • 37
  • 75
1

Using regex, you can use /[a-zA-z]/ (which matches the first letter in a string) together with search(), for every array item using a for loop, and when search(/[a-zA-Z]/) returns 0, stop and return the current index.

var arr = ['1', '1/2', 'fresh', 'tomatoes'];
for(var i = 0; i < arr.length; i++) {
  if(arr[i].search(/[a-zA-Z]/) == 0) {
    console.log(i);
    break;
  }
}

Here is another solution, this time using character codes:

var arr = ['1', '1/2', 'fresh', 'tomatoes'];
for(var i = 0; i < arr.length; i++) {
  var x = arr[i][0].charCodeAt();
  if((x >= 65 && x <= 90) || (x >= 97 && x <= 122)) {
    console.log(i);
    break;
  }
}
Wais Kamal
  • 5,858
  • 2
  • 17
  • 36
0

My suggestion:

function myFunction() {
var i;  
var str = ['1', '1/2', 'fresh', 'tomatoes'];
for(i=0; i<str.length; i++){
  if (str[i].charAt(0) >= 'a' && str[i].charAt(0) <= 'z') {
     console.log(i);
  break;    
    }
 }

}

ddy250
  • 281
  • 2
  • 5
  • 16