Java-Seekar
Java-Seekar

Reputation: 1770

Array Search by first character

Is there any way to search the javascript array which has the element which starts with the particular char without looping the array.

Example:

   var fruits = ["Banana", "Orange", "Apple", "Mango"];

From this array I want to check any element starts with the character 'M'. Note: Should not loop the array.

Upvotes: 0

Views: 112

Answers (7)

Michael Dziedzic
Michael Dziedzic

Reputation: 543

You could use the iterative method filter() like this:

var match = fruits.filter(function (item, index, array) {
    return item.charAt(0) === "M";
});

https://jsfiddle.net/lemoncurry/tydrgmoa/

Upvotes: 0

Captain Planet
Captain Planet

Reputation: 408

Use this code

var fruits = ["Banana", "Orange", "Apple", "Mango"];
var match = fruits.filter(function (item, index, array) {
    if(item.charAt(0) === "M")
         console.log(item);
});

http://jsfiddle.net/a02z99xg/4/

Upvotes: 0

winhowes
winhowes

Reputation: 8065

You could also do this:

var exists = fruits.some(function(element){return element[0] === "M"});

More info on .some() here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some

Upvotes: 0

Tschallacka
Tschallacka

Reputation: 28742

The only way you can do that is by making them a subpart of an associative array which defines the indexes.

So the moment you initialise/load up the array you define which characters are in there. This way you will only have to loop at the init or load functions of your values

mainIndex = new Array();
while(loadingarray.hasNext()) {
    var next = loadingarray.getNext();
    var indexchar = next.charAt(0);
    if(typeof mainIndex[indexchar] == 'undefined') {
        mainIndex[indexchar] = new Array();
    }
mainIndex[indexchar].push(next);
}

Upvotes: 1

Alex Kopachov
Alex Kopachov

Reputation: 733

you can use .filter function, but internally it still will use loop. In fact there is no way of how to check the full array without loop.

fruits.filter(function(item) { return item.substring(0, 1) == 'M'; });

Upvotes: 3

Akshaya Moorthy
Akshaya Moorthy

Reputation: 307

No built in function , create custom function.

Upvotes: -1

Arun P Johny
Arun P Johny

Reputation: 388406

If the array does not contains objects or the values does not contains , then use can join the array to create a string then use a regex

var fruits = ["Banana", "Orange", "Apple", "Mango"];
var exists = /,M/.test(fruits.join());
console.log(exists)

Upvotes: 1

Related Questions