Home > Net >  Avoid pushing duplicate objects to an angular array
Avoid pushing duplicate objects to an angular array

Time:12-16

I have multiple checkboxes in my angular application. When user checked and unchecked checkboxes I want to pass those true/false values into an array. It's happening from below code. But my problem is as you can see the below console.log, it has duplicate checkbox values(index 0 and 3 have same thing) and push it to the array.

I want to know how to check duplicate objects and avoid pushing object to the array.

.ts file

layerChange(e:any){
    var isChecked = e.target.checked;
    var id = e.target.attributes.id.nodeValue;
    const layer = {
      isChecked: isChecked,
      id: id,
    }
    this.layers.push(layer);
    console.log(this.layers);
  }

.html file

 <input id="population" (change)="layerChange($event)" type="checkbox">
 <input id="gender" (change)="layerChange($event)" type="checkbox">
 <input id="householdIncome" (change)="layerChange($event)" type="checkbox">

console.log(this.layers)

**0: {isChecked: true, id: 'population'}**
1: {isChecked: true, id: 'age'}
2: {isChecked: false, id: 'population'}
**3: {isChecked: true, id: 'population'}**

CodePudding user response:

You can check if an entry exists first using either :

 var id = e.target.attributes.id.nodeValue;
 var attr = this.layer.find(x => x.id === id);
    if(!attr)
      this.layers.push(layer);

or

this.layer.filter(x => x.id === id)

Edit

in your scenario is better to construct the array only one time in page load.

ngOnInit(): void {
    this.layer = [{id: 'age', isChecked: false}, {id:'population',isChecked: false}]
  }

and then alter the check state when user check/uncheck :-

layerChange(e:any){
    var isChecked = e.target.checked;
    var id = e.target.attributes.id.nodeValue;
    this.layer.find(x => x.id === id).isChecked = isChecked;
    console.log(this.layers);
  }

CodePudding user response:

You can create a string array which contains only ids and you can insert or remove elements from the array as per the selection

 layerChange(e:any) {
         const id = e.target.attributes.id.nodeValue;
         const index = this.layers.findIndex(el => el === id)
         if(index === -1) {
          this.layers.push(id);
         } else {
         this.layers.splice(index, 1)
         }
        
         console.log(this.layers);
       }
  • Related