-1

I'm trying to compare indexes of an array. However I'm not to sure I'm going about it correctly. My thoughts are:

let tempArray = [tempInfo1,tempInfo2];

if(tempArray[0] == tempArray[1]){
    console.log('true');
}else{
    console.log('false');
}

Am I headed in the right direction? Or is this completely off?

Essentially - I'm trying to make a 'matching game'. Clicking an element stores that element in a tempArray (tempInfo1), and clicking on a second element stores a second value in that array (tempInfo2). Then I'm trying to check if the values are the same - do something. If not do something else. Does this help?

ab3d_work
  • 187
  • 1
  • 16

3 Answers3

1

To head you in the right direction

You are probably working with a 4x4 of elements.

Lets say an element looks like this

HTML

<div id="card" value="cat"></div>

JavaScript

let lastSelected = null;
document.getElementById('card', (event) => {
    if(event.target.value === lastSelected.value){
      // remove both elements
    } else {
      lastSelected = event.target
    }
});
Pavlo
  • 1,117
  • 7
  • 13
0

First as mentioned in comments you are comparing values. Indexes are just 0, 1, 2, 3, 4... If you know what resides in an index that might be an option.

and actually that can fail if you're comparing object (and arrays that are a special type of object.)

Imagine this:

  var arrayOfDifferentTypes = [
  {
    somekey: "value"
  },
  {
    somekey: "value"
  },
  [1, 2, 3, 4],
  [1, 2, 3, 4],
  "data",
  "data",
  18,
  18
];

console.log(arrayOfDifferentTypes[0] === arrayOfDifferentTypes[1]); // false
console.log(arrayOfDifferentTypes[2] === arrayOfDifferentTypes[3]); // false
console.log(arrayOfDifferentTypes[4] === arrayOfDifferentTypes[5]); // true
console.log(arrayOfDifferentTypes[6] === arrayOfDifferentTypes[7]); // true

As you can see it will fail. You can check this or this one for that kind of comparison.

0

You are not comparing indices of the array and as per your description that you are trying to make matching game which matches first two values in array then YES you're headed in right direction but use === instead of == to compare the values.