Remover objetos repetidos de un array

Code with Edd

Remover objetos repetidos de un array en base a otro array de objetos en javascript/typescript.

Siguiendo el siguiente escenario tenemo lo siguiente:

El array de objetos «products» es nuestro array principal. El array de objetos «moreProducts» es el array que se usará para agregar más productos al array «products».

Antes de agregar los items del array «moreProducts» se requiere validar los siguiente: los items del array «moreProducts» si estan repetidos en el array «products», entonces, se deberán eliminar los repetidos del array «products».

public products = [
    { itemCode: 'A', itemName: 'Item A', quantity: 2 }, 
    { itemCode: 'A', itemName: 'Item A', quantity: 1 }, 
    { itemCode: 'B', itemName: 'Item B', quantity: 1 },
    { itemCode: 'C', itemName: 'Item C', quantity: 1 }
];

public moreProducts = [
    { itemCode: 'A', itemName: 'Item A', quantity: 1 },
    { itemCode: 'H', itemName: 'Item H', quantity: 1 }
];
removeObjects() {
    let newData: Array<any> = [];
    if (this.products.length > 0) {
        newData = this.products.filter(function (obj) {
        return !this.has(obj.itemCode);
        }, new Set(this.moreProducts.map((obj) => obj.itemCode)));
    }
    return newData;
}
ngOnInit() {
    this.products = this.removeObjects();
    this.moreProducts.forEach((element) => {
        this.products.push(element);
    });
    console.log('Products', this.products);
}
// RESULTADO:
Products [{…}, {…}, {…}, {…}]
0: Object
    itemCode: "B"
    itemName: "Item B"
    quantity: 1
    <prototype>: Object
1: Object
    itemCode: "C"
    itemName: "Item C"
    quantity: 1
    <prototype>: Object
2: Object
    itemCode: "A"
    itemName: "Item A"
    quantity: 1
    <prototype>: Object
3: Object
    itemCode: "H"
    itemName: "Item H"
    quantity: 1
    <prototype>: Object

Referencia

Stackoverflow

Remover objetos repetidos de un array
Web | + posts

Full Stack Web Developer && SDK SAPB1 Developer.

Melómano, Gamer (Xbox), Comprador compulsivo de Amazon y Posiblemente con TDAH.

Scroll hacia arriba