0

I have this array which is an array of name collection

var nameCollection = ['Andre', 'Ann', 'Bob', 'Bill', 'Cindy', 'Camille', ...];

How can I get the position of the first text which start with A, B or Z dynamically? I turn around to find the solution but I think someone didn't ask this question before.

If someone could give me an example, it will be welcome! :)

Radonirina Maminiaina
  • 6,958
  • 4
  • 33
  • 60

4 Answers4

3

In my humble opinion, this is the best way to implement @Suppen's firstToStartWith function:

var nameCollection = ["Andre", "Ann", "Bob", "Bill", "Cindy", "Camille"];

alert(firstToStartWith("C", nameCollection));

function firstToStartWith(chr, arr) {
    var len = arr.length;
    var idx = 0;

    while (idx < len) {
        var str  = arr[idx];
        var elem = str.charAt(0);
        if (elem === chr) return idx;
        idx++;
    }

    return -1; // not found
}

The reason I use str.charAt(0) instead of str[0] is because the bracket notation for strings is not cross-browser compatible and because it gives the illusion that strings in JavaScript are mutable.

Read the following question and answers for more details:

string.charAt(x) or string[x]?

Hope that helps.

Community
  • 1
  • 1
Aadit M Shah
  • 72,912
  • 30
  • 168
  • 299
  • While I do agree that str.charAt() may be more readable and generally better, I don't like the "not cross-browser compatible" argument in this case. It may not work in IE7 or previous, but if we keep supporting them, the users will have no reason to get rid of it, and we will need to support it forever. Of course, if the bracket notation is not part of the ECMAscript standard, it shouldn't be used. I don't know if it is. – Suppen Feb 13 '15 at 08:53
  • Either way, there are more cons than pros of using the bracket notation over `.charAt`. – Aadit M Shah Feb 13 '15 at 08:58
2

Define a function to find what you asked for

function firstToStartWith(letter, array) {
    for (var i = 0; i < array.length; i++) {
        if (array[i].charAt(0) == letter) { // If first letter in ith element in the array matches the provided letter
            return i;
        }
    }
    return -1;
}

Then call it on your array

var nameCollection = ['Andre', 'Ann', 'Bob', 'Bill', 'Cindy', 'Camille', ...];
firstToStartWith("C", nameCollection); // Returns 4




Thanks to @Aadit M Shah for the explanation of why to use str.charAt(0) instead of str[0]

Suppen
  • 836
  • 1
  • 6
  • 21
0

this is basically an improved version of Suppens idea:

var items = ['Apple', 'Peach', 'Andrew', 'Bill', 'Cindy', 'Camille'];

console.log(findKeyStartingWith('b', items, true));

/**
*   This method returns the position of the first item starting with the symbol or false if there was no entry starting with the letter
*
*   @param string letter                character to search the array for
*   @param array elements               the array to be searched
*   @param boolean matchCase            true if the search has to be case sensitive ('a' vs 'A')
*/
function findKeyStartingWith(letter, elements, matchCase) { 
    var posCount = 0;
    for(item in elements) {
        var tmpItem = elements[item];
        //exactly match the case
        if(tmpItem.charAt(0) == letter) {
            return posCount;
        }
        //check for lowercase or uppercase character
        else if(!matchCase && (tmpItem.charAt(0) == letter.toUpperCase() || tmpItem.charAt(0) == letter.toLowerCase())) {
            return posCount;
        }
        posCount++;
    }
    return false;
}
  • I would avoid using `for..in` statements. Also, why are you making the code more complicated by allowing case insensitive matches? The OP doesn't require it. – Aadit M Shah Feb 13 '15 at 09:03
  • Because there is a difference in the characters and therefore it could result in mistakes or wrong results. – Arthega Asdweri Feb 13 '15 at 09:08
-1

One way to achieve that would be to use a combination of the indexOf function of javascript in combination with regular expressions.

The way you can go about this is by modifying the built-in String object of javascript to add support of regular expressions to the indexOf function. It is explained quite nicely here Javascript-string-indexOf that allows use of regular expressions

Once you do this, then all you need to do is iterate over the array comparing each element to check for the character you are looking for, store its index in a variable and voila!

Community
  • 1
  • 1
Parth
  • 367
  • 6
  • 18
  • Modifying built in objects are considered bad practice. Also, mixing regular expressions into this is uneccesarily complicated. – Suppen Feb 13 '15 at 08:41
  • It may be a bad practice in general, but can you point out if there is some disadvantage of using this approach in this specific case? And the regular expression to use here would be pretty straight forward. – Parth Feb 13 '15 at 08:48
  • There's nothing wrong with your approach (although you should really show some code). However, it just seems to me that you are a [seasoned professional](http://www.ariel.com.au/jokes/The_Evolution_of_a_Programmer.html). – Aadit M Shah Feb 13 '15 at 08:54