简体   繁体   中英

Get the difference between two arrays

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"
}]

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM