How to get the difference between two arrays of objects in JavaScript

前端 未结 18 1359
没有蜡笔的小新
没有蜡笔的小新 2020-11-22 04:45

I have two result sets like this:

// Result 1
[
    { value: \"0\", display: \"Jamsheer\" },
    { value: \"1\", display: \"Muhammed\" },
    { value: \"2\",         


        
18条回答
  •  一个人的身影
    2020-11-22 05:11

    You can create an object with keys as the unique value corresponding for each object in array and then filter each array based on existence of the key in other's object. It reduces the complexity of the operation.

    ES6

    let a = [{ value:"4a55eff3-1e0d-4a81-9105-3ffffd7521d642", display:"Jamsheer"}, { value:"644838b3-604d-4899-8b78-09e4799f586f", display:"Muhammed"}, { value:"b6ee537a-375c-45bd-b9d4-4dd84a75041d", display:"Ravi"}, { value:"e97339e1-939d-47ab-974c-1b68c9cfb536", display:"Ajmal"},  { value:"a63a6f77-c637-454e-abf2-dfb9b543af6c", display:"Ryan"}];
    let b = [{ value:"4a55eff3-1e0d-4a81-9105-3ffffd7521d642", display:"Jamsheer", $$hashKey:"008"}, { value:"644838b3-604d-4899-8b78-09e4799f586f", display:"Muhammed", $$hashKey:"009"}, { value:"b6ee537a-375c-45bd-b9d4-4dd84a75041d", display:"Ravi", $$hashKey:"00A"}, { value:"e97339e1-939d-47ab-974c-1b68c9cfb536", display:"Ajmal", $$hashKey:"00B"}];
    
    let valuesA = a.reduce((a,{value}) => Object.assign(a, {[value]:value}), {});
    let valuesB = b.reduce((a,{value}) => Object.assign(a, {[value]:value}), {});
    let result = [...a.filter(({value}) => !valuesB[value]), ...b.filter(({value}) => !valuesA[value])];
    console.log(result);

    ES5

    var a = [{ value:"4a55eff3-1e0d-4a81-9105-3ffffd7521d642", display:"Jamsheer"}, { value:"644838b3-604d-4899-8b78-09e4799f586f", display:"Muhammed"}, { value:"b6ee537a-375c-45bd-b9d4-4dd84a75041d", display:"Ravi"}, { value:"e97339e1-939d-47ab-974c-1b68c9cfb536", display:"Ajmal"},  { value:"a63a6f77-c637-454e-abf2-dfb9b543af6c", display:"Ryan"}];
    var b = [{ value:"4a55eff3-1e0d-4a81-9105-3ffffd7521d642", display:"Jamsheer", $$hashKey:"008"}, { value:"644838b3-604d-4899-8b78-09e4799f586f", display:"Muhammed", $$hashKey:"009"}, { value:"b6ee537a-375c-45bd-b9d4-4dd84a75041d", display:"Ravi", $$hashKey:"00A"}, { value:"e97339e1-939d-47ab-974c-1b68c9cfb536", display:"Ajmal", $$hashKey:"00B"}];
    
    var valuesA = a.reduce(function(a,c){a[c.value] = c.value; return a; }, {});
    var valuesB = b.reduce(function(a,c){a[c.value] = c.value; return a; }, {});
    var result = a.filter(function(c){ return !valuesB[c.value]}).concat(b.filter(function(c){ return !valuesA[c.value]}));
    console.log(result);

提交回复
热议问题