You can't simply compare two objects in javascript because the references instead of the values of this objects are compared.
You can check this link to learn about that:
https://medium.com/javascript-in-plain-english/comparing-objects-in-javascript-ce2dc1f3de7f
If you prefer simplicity over profundity and the objects that you are putting inside de array are'nt to complex you could try Json.stringify() this transforms your object in a string making it easy to compare.
Notice that in the next example i changed the order of the array and the names for readibility.
var firstArray = [
{
nb: 'rouge',
xb: 'rouge',
x: 12,
},
{
nb: 'red',
xb: 'rouge',
x: 12,
},
{
nb: 'violet',
xb: 'violet',
x: 12,
},
];
var secondArray = [
{
nb: 'rouge',
xb: 'rouge',
x: 12
},
{
nb: 'red',
xb: 'rouge',
x: 12
}
];
function difference(firstArray, secondArray) {
return firstArray.filter(firstArrayElement => {
return !isContainedInSecondArray(firstArrayElement, secondArray);
});
}
function isContainedInSecondArray(firstArrayElement, secondArray) {
return secondArray.find(secondArrayElement => {
if (JSON.stringify(firstArrayElement) == JSON.stringify(secondArrayElement)) {
return true;
}
});
}
//prints [ { nb: 'violet', xb: 'violet', x: 12 } ]
console.log(difference(firstArray, secondArray));
//prints []
console.log(difference(secondArray, firstArray));