Search code examples
javascriptangulartypescriptrowsag-grid

How to Remove duplicate rows in AG Grid?


I was experimenting with AG Grid in Angular, and immediately facing a challenge.

enter image description here

I want to make sure that AG Grid shows unique rows.

Should I iterate over the Grid and remove duplicate rows or check if a row with those values already exists in the Grid?

I was thinking to use a Set for this challenge. I hope to receive some help finding the most efficient solution in code.

grid-test.component.html

<!-- Button to clear selection -->
<button (click)="clearSelection()">Clear Selection</button>
<!-- AG Grid Angular Component -->
<ag-grid-angular
   style="width: 70%; height: 100%; display: block; margin-left: auto; margin-right: auto;"
   class="ag-theme-alpine"
   [columnDefs]="columnDefs"
   [defaultColDef]="defaultColDef"
   [rowData]="rowData$ | async"
   [rowSelection]="'multiple'"
   [animateRows]="true"
   (gridReady)="onGridReady($event)"
   (cellClicked)="onCellClicked($event)"
 ></ag-grid-angular>

grid-test.component.ts

import { HttpClient } from '@angular/common/http';
import { Component, OnInit, ViewChild } from '@angular/core';
import { AgGridAngular } from 'ag-grid-angular';
import { CellClickedEvent, ColDef, GridReadyEvent } from 'ag-grid-community';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-grid-test',
  templateUrl: './grid-test.component.html',
  styleUrls: ['./grid-test.component.css']
})
export class GridTestComponent implements OnInit {

  ngOnInit(): void {
  }
  
  // Each Column Definition results in one Column.
 public columnDefs: ColDef[] = [
  { field: 'make'},
  { field: 'model'},
  { field: 'price' }
];

// DefaultColDef sets props common to all Columns
public defaultColDef: ColDef = {
  sortable: true,
  filter: true,
};

// Data that gets displayed in the grid
public rowData$!: Observable<any[]>;

// For accessing the Grid's API
@ViewChild(AgGridAngular) agGrid!: AgGridAngular;

constructor(private http: HttpClient) {}

// Example load data from sever
onGridReady(params: GridReadyEvent) {
  this.rowData$ = this.http
    .get<any[]>('https://www.ag-grid.com/example-assets/row-data.json');
}

// Example of consuming Grid Event
onCellClicked( e: CellClickedEvent): void {
  console.log('cellClicked', e);
}

// Example using Grid's API
clearSelection(): void {
  this.agGrid.api.deselectAll();
}

}

Solution

  • There are multiple approaches you can take to ensuring there are no duplicate rows that have the same data.

    One approach would be to iterate over every row using api.forEachNode and keep track if a row already exists.

    Another approach would be to create a Set from the current row data and then convert that back into an array. You can see an example of this being implemented in the following plunkr.

      onBtnRemove() {
        const rowDataSlash = new Set(
          this.rowData.map((row) => row.make + '/' + row.model + '/' + row.price)
        );
        
        const newRowData = Array.from(rowDataSlash).map((row) => {
          const rowParts = row.split('/');
          return { make: rowParts[0], model: rowParts[1], price: rowParts[2] };
        });
        this.rowData = newRowData;
      }