1

Below is my code, here I want to push the subModule object into the selectedPieces array if submodule.active is true and if it is not present inside the selectedPieces array. But in my code, it is inserting values multiple times after inserting two values. The Pieces object is as below and activateClass is my method on which if I will click I will get the piece object.

Pieces = {
  pieceId: 1,
  img: '../../../../assets/img/piece.PNG',
  letter: 'O',
  active: false
}

activateClass(subModule){
    subModule.active = !subModule.active;  
    subModule.activeli = !subModule.activeli; 
    if(this.selectedPieces.length == 0 && subModule.active == true){
      this.selectedPieces.push(subModule);
    }
    else{
    for(let i=0;i< this.selectedPieces.length; i++){
      if(subModule.active == true && subModule.pieceId !== this.selectedPieces[i].pieceId){
        this.selectedPieces.push(subModule);
      }
      if(subModule.active == false && subModule.pieceId == this.selectedPieces[i].pieceId){
        this.selectedPieces.splice(i);
      }
    }
    }
   
    console.log(this.selectedPieces);
  }
Sebastian Kaczmarek
  • 8,120
  • 4
  • 20
  • 38
  • pieceId and pieceid are different. Please check casing. Also splice method need to have second parameter if you want to delete that only one element. – CodeThing Feb 24 '23 at 11:54
  • For the first 2 time it is inserting the values correctly. After that for 3rd value it is inserting it twice for 4th value it is inserting it 4times duplicate values. Similarly splice is also not working – tripti tiwari Feb 24 '23 at 11:59
  • That's expected because you are pushing inside loop. So for every item in the array it checks the condition and push supplied element. – CodeThing Feb 24 '23 at 12:13
  • Please help me with the correct code – tripti tiwari Feb 24 '23 at 12:17

1 Answers1

0

Try this

activateClass(subModule){
  subModule.active = !subModule.active;  
  subModule.activeli = !subModule.activeli; 
  if (this.selectedPieces.length === 0 && subModule.active === true){
    this.selectedPieces.push(subModule);
  } else {
    let index = this.selectedPieces.findIndex((piece) => piece.pieceId === subModule.pieceId);
    if (subModule.active === true && index === -1) {
      this.selectedPieces.push(subModule);
    }
    if (subModule.active === false && index >= 0) {
      this.selectedPieces.splice(index, 1);
    }
  }

  console.log(this.selectedPieces);
}
CodeThing
  • 2,580
  • 2
  • 12
  • 25