Javascript search an array for a value and get its key

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

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 :)


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

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