shohamh
shohamh

Reputation: 317

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.

Upvotes: 17

Views: 52586

Answers (5)

Jacquen
Jacquen

Reputation: 1116

If you plan to find the indices of different values for a particular array a lot, it may be better to make an object with key-value pairs that map to the values and indices of the array.

const letters = ["a", "b", "c"]
const letterIndices = letters.reduce((acc, letter, index) => 
    Object.assign(acc, {[letter]: index}), {}
)

letterIndices["b"] // gives 1

Upvotes: 0

Wes Ruvalcaba
Wes Ruvalcaba

Reputation: 846

This is a method on the Array Prototype now: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex

var array1 = [5, 12, 8, 130, 44];

function findFirstLargeNumber(element) {
  return element > 13;
}

console.log(array1.findIndex(findFirstLargeNumber));
// expected output: 3

Upvotes: 2

The Internet
The Internet

Reputation: 8103

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

Upvotes: 27

Iqbal Djulfri
Iqbal Djulfri

Reputation: 708

function arraySearch(arr, val) {
  var index;
  for (var i = 0; i < arr.length; i++) {
    // use '===' if you strictly want to find the same type
    if (arr[i] == val) {
      if (index == undefined) index = i;
      // return false if duplicate is found
      else return false;
    }
  }

  // return false if no element found, or index of the element
  return index == undefined ? false : index;
}

Hope this helps :)

Upvotes: 1

Anoop
Anoop

Reputation: 23208

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

Upvotes: 15

Related Questions