Javascript looks up an array for the value and gets its key

I want to create a function that works as follows:

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

if it finds the value in the array, it will return the key where it will find the value. If there is more than one result (more than one key) or no results at all (nothing was found), the function returns 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 that does not work. When it needs to find something, it returns false instead of key (i).

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

Thank you, and I'm very sorry if my English was not clear enough.

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

You can use indexOf to get jsfiddle key

 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 
+12
source
 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 :)

+2
source

Now this method is used in the Array prototype: 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 
+1
source

If you plan to find a lot of indices of different values ​​for a particular array, it might be better to create 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 
0
source

All Articles