shohamh
shohamh

Reputation: 317

Javascript - Check if a certain index has a certain value in an array

I have an array with 144 indexes, that I fill with data from a form. I want to check if a certain index contains a certain value, and I don't know if such function exists in JavaScript, or how to make said function.
Can you help me make a function that gets an array, a certain index and a certain value as parameters and return true if it exists?

An example:

var board = new Array();
board.push('X');
board.push('O');
function inArrayatindex(array, index, value)
{
/* if(certain code that i need help with...)
{
return true;
}
}
inArrayatindex(board, 2, 'O'); //returns true
inArrayatindex(board, 2, 'o'); // returns false
inArrayatindex(board, 3, 'X'); // returns false

Upvotes: 1

Views: 1801

Answers (3)

Lars Flieger
Lars Flieger

Reputation: 2534

Update 2022

With ES2022 you can use Array.prototype.at():

function isValueAtIndex(array, index, value) {
    return array.at(index) === value
}
  • You can check from the end with negative index.
  • You do not have to check length since at will return undefinded if the given index can not be found.

Upvotes: 0

AboQutiesh
AboQutiesh

Reputation: 1716

I think that is what you need,

function inArray(array,valueToMatch){

  var myArray = array
  var index = -1;

  for(int i=0;i<myArray.length;i++){
      if(myArray[i].match(valueToMatch)){
        index = i;
      }   
   }

  return index;
}

note : array parameter your 144 index array

valueToMatch parameter is the value you search for

Upvotes: 0

Gregor
Gregor

Reputation: 4434

try this:

function check(array, index, value) {
    if(index < 0 || index >= array.length) {
         return false;
    }
    return array[index] === value;
}

Upvotes: 4

Related Questions