0

I am pushing row dynamically on add new button click in my form. The new data will be added in oldData array in the form of object.

I want to match all values of newData object with oldData array, if newData object with same values is available in oldData array of objects, Then code will console error else it push the row.

Can anyone please help me to make my function working.

Shubham pandey
  • 37
  • 1
  • 11
  • This is not a question of angular itself. The error should show up if one value exists or ALL values are the same? – DonJuwe Feb 16 '22 at 12:46
  • @DonJuwe, If all values are same then only error will throw – Shubham pandey Feb 16 '22 at 13:00
  • Yong Shun has the correct answer, which is "no, not out of the box", do use a library like lodash. Elegantly, he does so by linking to a previous question/answer! – JSmart523 Feb 16 '22 at 13:38

2 Answers2

0

I do it like this:

private allElementExists(newData: any[], oldData: any[]): boolean {
    for (const item of newData) {
        var verifyItem = oldData.find(x => x.id === item.id);
        if (verifyItem === undefined) {
            return false;
        }
    }
    return true;
}

Here you have a function that compares the two objets as you putted in your question

Here is an example in stackblitz using this function

https://stackblitz.com/edit/angular-xscnkf?file=src%2Fapp%2Fapp.component.html

José Polanco
  • 574
  • 4
  • 19
0

If oldData keeps several objects, you can do: if(!oldData.includes(newData))

EDIT 1 (for original code in description): if both are just single objects, simple comparison will do: if(oldData! = newData)

EDIT 2 (for edited code in description):

addNewType(rowdata) {
    const newData = JSON.stringify(rowdata.value);
    const oldData = JSON.stringify(this.items.value);
    if(oldData.includes(newData)){
        console.log('This element already exists in the detail list');
    }
    else this.addItem(this.createItem(null));           
}

EDIT 3: if oldData has newData at least twice

addNewType(rowdata) {
    const newData = JSON.stringify(rowdata.value);
    const oldData = JSON.stringify(this.items.value);
    if((oldData.split(newData).length - 1) >= 2){
        console.log('This element already exists in the detail list at least TWICE');
    }
    else this.addItem(this.createItem(null));           
}

or:

addNewType(rowdata) {
    const newData = JSON.stringify(rowdata.value);
    const oldData = JSON.stringify(this.items.value);
    let newReg= new RegExp(newData, "g");
    if((oldData.match(newReg) || []).length >= 2){
        console.log('This element already exists in the detail list at least TWICE');
    }
    else this.addItem(this.createItem(null));           
}
Misha Mashina
  • 1,739
  • 2
  • 4
  • 10