Search code examples
reactjsarraystypescriptchangelog

How to compare two arrays of objects and get the values that differ in React?


I am trying to do a changelog for my website.

For expample, I have the initial array, call it initArray:

[
    {
        "id": 1,
        "val1": "2023-08-28",
        "val2": 1,
        "val3": "",
        "val4": "",
    },
    {
        "id": 2,
        "val1": "2023-08-28",
        "val2": 2,
        "val3": "",
        "val4": ""
    },
    {
        "id": 3,
        "val1": "2023-08-28",
        "val2": 0,
        "val3": "",
        "val4": ""
    }
]

And then, I have the second array, call it changedArray:

[
    {
        "id": 1,
        "val1": "2023-08-28",
        "val2": 1,
        "val3": "test",
        "val4": "test1"
    },
    {
        "id": 2,
        "val1": "2023-08-28",
        "val2": 2,
        "val3": "test2",
        "val4": "test3"
    },
    {
        "id": 3,
        "val1": "2023-08-28",
        "val2": 0,
        "val3": "",
        "val4": ""
    }
]

So, I need to find the values that were changed and output the names of these values and the values themselves. How can this be done?

The expected outcome would be like:

[
    {
        "changedValue": "val3", 
        "previousValue": "", 
        "newValue": "test"
    },
    //And so on...
] 

The number of elements in the arrays is constant, there can't be deleted or added elements – only changed.


Solution

  • You could use Array#reduce function to loop over the array of objects and compare the values with the corresponding object in the new array.

    const compare = (arr1, arr2) => 
       arr1.reduce((acc, next, idx) => {
          Object.entries(next).forEach(([key, val]) => {
             const newValue = arr2[idx]?.[key];
             if (newValue && val !== newValue) {
                acc.push({
                   changedValue: key,
                   previousValue: val,
                   newValue,
                })
             }
          });
          
          return acc;
       }, []);
       
    const data1=[{"val1":1,"val2":"2023-08-28","val3":1,"val4":"","val5":"",},{"val1":2,"val2":"2023-08-28","val3":2,"val4":"","val5":""},{"val1":3,"val2":"2023-08-28","val3":0,"val4":"","val5":""}];
    const data2=[{"val1":1,"val2":"2023-08-28","val3":1,"val4":"test","val5":"test1"},{"val1":2,"val2":"2023-08-28","val3":2,"val4":"test2","val5":"test3"},{"val1":3,"val2":"2023-08-28","val3":0,"val4":"","val5":""}];
       
    console.log(compare(data1, data2));