Just as it is done in php
( link ) but I would like to do it in javascript
.
var data1 = [{
"id": 1,
"nombre": "Mezcla"
},
{
"id": 6,
"nombre": "No Se"
},
{
"id": 5,
"nombre": "Etiquetado"
},
{
"id": 4,
"nombre": "Vaciado"
},
{
"id": 3,
"nombre": "Llenado"
},
{
"id": 2,
"nombre": "Esterilizacion"
}
];
console.log(data1);
var data2 = [{
"id": 1,
"nombre": "Mezcla"
},
{
"id": 4,
"nombre": "Vaciado"
},
{
"id": 3,
"nombre": "Llenado"
},
{
"id": 2,
"nombre": "Esterilizacion"
}
];
console.log(data2);
Update 1:
That of those 2 arrays
I return the following:
var data3 = [{
"id": 6,
"nombre": "No Se"
},
{
"id": 5,
"nombre": "Etiquetado"
}
];
console.log(data3);
I don't know if this is the way you are looking for but I add it since it reaches the expected result. loop through the two arrays with two
For
simple ones. then go comparing the differences between the fields.This can obviously be done with pure javascript, but for working with collections, there are already well-proven tools like underscore and lodash .
The following solution uses the find method of lodash.
The main difficulty of your question is that in javascript two objects are not equal to each other even though they have the same properties. For the same look for the existence of a certain object using the method
indexOf
It will always say that the object is not in the array. It would be necessary to implement an equality function that is fulfilled when the enumerable properties of two objects coincide, and then go through both arrays in nested loops, checking if there are elements that fulfill that custom function. I'd rather not reinvent the wheel.
Here I leave a version in pure JavaScript, although it is a bit "ugly". The idea is to convert the objects to strings, to make them easier to work with. And the steps would be:
The code would look like this:
If you don't want to convert objects to strings, you can define your own compare function and traverse the arrays looking for duplicate elements (instead of using
indexOf
).Something like this:
Here my version of
array_diff_assoc
which:1 o más
arrangementsJSON.stringify
arr1
that are not in everything else .demonstration:
Based on your question I have assumed that the objects will always be simple, without methods or html nodes, otherwise the solution would be a bit more complex
My version for this question