-2

I need to get only the difference between two arrays

I tried:

let arr1 = {
    "data": [{
        "id": "EID_Floss",
        "name": "Floss",
        "te": "dd"
    }]
}
let arr2 = {
    "data": [{
        "id": "EID_Floss",
        "name": "Floss"
    }]
}
JSON.stringify(arr2.data.filter((x) => !arr1.data.includes(x)))

Result:

[{
    "id": "EID_Floss",
    "name": "Floss"
}]

How to get only this:

[{
   "te": "dd"
}]
Cristik
  • 30,989
  • 25
  • 91
  • 127
John
  • 1
  • 3
  • Why is `arr1` not an array? What if the `data` attributes have more than one element? Please be more detailed in your question. – Aplet123 Dec 20 '20 at 17:18
  • How do you define "difference between two arrays"? Do you mean throw out elements of one array that are not in the other? – Code-Apprentice Dec 20 '20 at 17:18
  • Are you trying to take the difference of the individual objects in the array? Is this by key, or both key and value? – SuperStormer Dec 20 '20 at 17:19
  • Do you really want the difference between two arrays? Or do you want the difference between each object in the arrays? – Code-Apprentice Dec 20 '20 at 17:19
  • Note that `arr1` and `arr2` are **objects**, not arrays. Let's simplify your example to just be arrays instead of the unecessary complex nesting. – Code-Apprentice Dec 20 '20 at 17:20
  • the result is [{ "id": "EID_Floss", "name": "Floss" }] I don't need the same data I need difference between them – John Dec 20 '20 at 17:23
  • take a look at this questions: https://stackoverflow.com/questions/21987909/how-to-get-the-difference-between-two-arrays-of-objects-in-javascript – crivella Dec 20 '20 at 17:26

1 Answers1

1

Look at this simpler example:


arr1 = ["foo", "bar"];
arr2 = ["foo", "bar", "foobar"];

arr3 = arr2.filter((x) => !arr1.includes(x));
console.log(arr3);

This does exactly what you exect and the output is:

["foobar"]

The problem with your example, is that the arrays in arr1.data and arr2.data contain objects. You are comparing the object

{
        "id": "EID_Floss",
        "name": "Floss",
        "te": "dd"
}

from arr1 with the object

{
        "id": "EID_Floss",
        "name": "Floss"
}

from arr2. Since these are not equal, your filter does not remove the object from the array.

Note that this is an all or nothing operation since you are filtering the array of objects. Instead, it sounds like you want to filter the keys in each object. So you need to use Object.keys() or Object.values() to iterate over the contents of the objects.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268