javascript arrays of object comparing

Tags: , ,



I have a project when I get some data from a route in node and I need to compare with the last data I received to see if something changed, basically 2 arrays of objects. For the comparasion I used JSON.stringify(array1) = JSON.stringify(array2), but after I compare the arrays I want to put the value of array2 in array1, so after I receive one more value for array2 in the request, to be able to comparte with the last value witch is stored in array1. The structure of function I thought it is going to work is something like that

if(JSON.stringify(array1) != JSON.stringify(array2)) {
  console.log("not equal...");
  array1 = array2;
}

In array2 is what I receive on server, and after I compare their stringfy value, if they are not equal. change the value of array1 to exactly array2. After some research I understood that the array1 = array2 part it’s the problem, but I can’t figure out how to put the value of array2, which is an array of Objects, in array1. The structure of array2 is something like that

  [{
   data1: value,
   data2: value

  }
  { data1: value,
    data2: value,
  }
  { data1: value,
    data2: value 
  }]

Answer

Using the = operator simply creates a pointer to the original array as it is a mutable object. Change a value on that, and both variables will see it. There are several common ways to create a new array from an existing one:

const array1 = [...array2];

const array1 = array2.slice();

const array1 = [].concat(array2);

Or, you could use:

const array1 = JSON.parse(JSON.stringify(array2));

This will convert nested arrays etc into strings and back into a new array.



Source: stackoverflow