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

前端 未结 18 1056
没有蜡笔的小新
没有蜡笔的小新 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:12

    you can do diff a on b and diff b on a, then merge both results

    let a = [
        { value: "0", display: "Jamsheer" },
        { value: "1", display: "Muhammed" },
        { value: "2", display: "Ravi" },
        { value: "3", display: "Ajmal" },
        { value: "4", display: "Ryan" }
    ]
    
    let b = [
        { value: "0", display: "Jamsheer" },
        { value: "1", display: "Muhammed" },
        { value: "2", display: "Ravi" },
        { value: "3", display: "Ajmal" }
    ]
    
    // b diff a
    let resultA = b.filter(elm => !a.map(elm => JSON.stringify(elm)).includes(JSON.stringify(elm)));
    
    // a diff b
    let resultB = a.filter(elm => !b.map(elm => JSON.stringify(elm)).includes(JSON.stringify(elm)));  
    
    // show merge 
    console.log([...resultA, ...resultB]);

提交回复
热议问题