1

I'm facing an issue with comparing two Objects.

I'm comparing an incoming Object, with an Object Array, to see if the Object is already in the array.

I tried two methods:

(betTemps is the Array of Objects, tempBet is the current object which should be compared.)

var duplicate = false;
for (let bet of this.betTemps) {
console.log(tempBet);
  console.log(bet);
  if(bet === tempBet) {
    console.log("reached");
    duplicate = true;
    break;
  }
}

The if afterwards:

.. else if(duplicate){
  alert("The Bet is already in the List");
} ...

Console Output after adding an Object which is already in the Array:

Console Output Screenshot

enter image description here

As you can see, they are equal, still the other Object is added to the array.

I tried using this method too with indexOf:

if(this.betTemps.indexOf(tempBet) > -1){
  alert("The Bet is already in the List");
}

Console Output after adding an Object which is already in the Array:

Console Output Screenshot

enter image description here

PS:

The code before the comparison:

  addBet(bet, index){
var tempBet = Object.assign({}, bet);
var select = (document.getElementById('select'+index)) as HTMLSelectElement;
select = select.options as HTMLSelectElement;
let count = 0;

tempBet.category = [];
for(let i = 0; i < 3; i++) {
    if (select[i].selected) {
      tempBet.category.push(select[i].value):
      count++;
    }
}

The code after the comparison:

if (count == 0) {
  alert("There has to be at least one Category choosen!");
} else if(duplicate     <- This part changes individually which method you use ->){
  alert("The Bet is already in the List");
} else {
  this.betTemps.push(tempBet);
}
Slava Ivanov
  • 6,666
  • 2
  • 23
  • 34
filip
  • 628
  • 2
  • 8
  • 31

1 Answers1

1

The best way to check if an object is in an array is using the array includes function: Like if I want to check if A object is in B array I would check (A === B.includes(A))

user9069254
  • 153
  • 2
  • 12