Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript search an array for a value and get its key

I want to make a function that works like this:

function arraySearch(array, valuetosearchfor)
{
// some code
}

if it finds the value in the array, it will return the key, where it found the value. If there is more than one result (more than one key), or no results at all (nothing found), then the function will return FALSE.

I found this code:

function arraySearch(arr,val) 
        {
            for (var i=0; i<arr.length; i++)
                {
                    if (arr[i] == val) 
                    {                    
                        return i;
                    }
                    else 
                    {
                        return false;
                    }
                }
        }

and used it like this:

var resultofarraycheck = arraySearch(board, chosen);
                if (resultofarraycheck === false) 
                {
                       document.getElementById(buttonid).value;
                       chosen = 0;
                }

But it doesn't seem to work. When it should find something, it returns false instead of the key (i).

How can I fix this, or what am I doing wrong?

Thanks, and I'm sorry if my English wasn't clear enough.

like image 878
shohamh Avatar asked Oct 28 '12 14:10

shohamh


2 Answers

function arraySearch(arr,val) {
    for (var i=0; i<arr.length; i++)
        if (arr[i] === val)                    
            return i;
    return false;
  }
like image 61
The Internet Avatar answered Sep 20 '22 14:09

The Internet


You can use indexOf to get key jsfiddle

if(!Array.prototype.indexOf){
    Array.prototype.indexOf = function(val){
        var i = this.length;
        while (i--) {
            if (this[i] == val) return i;
        }
        return -1;
    } 
}

    var arr = ['a','b','c','d','e'];

    var index = arr.indexOf('d'); // return 3
like image 23
Anoop Avatar answered Sep 16 '22 14:09

Anoop