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

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

    In addition, say two object array with different key value

    // Array Object 1
    const arrayObjOne = [
        { userId: "1", display: "Jamsheer" },
        { userId: "2", display: "Muhammed" },
        { userId: "3", display: "Ravi" },
        { userId: "4", display: "Ajmal" },
        { userId: "5", display: "Ryan" }
    ]
    
    // Array Object 2
    const arrayObjTwo =[
        { empId: "1", display: "Jamsheer", designation:"Jr. Officer" },
        { empId: "2", display: "Muhammed", designation:"Jr. Officer" },
        { empId: "3", display: "Ravi", designation:"Sr. Officer" },
        { empId: "4", display: "Ajmal", designation:"Ast. Manager" },
    ]
    

    You can use filter in es5 or native js to substract two array object.

    //Find data that are in arrayObjOne but not in arrayObjTwo
    var uniqueResultArrayObjOne = arrayObjOne.filter(function(objOne) {
        return !arrayObjTwo.some(function(objTwo) {
            return objOne.userId == objTwo.empId;
        });
    });
    

    In ES6 you can use Arrow function with Object destructuring of ES6.

    const ResultArrayObjOne = arrayObjOne.filter(({ userId: userId }) => !arrayObjTwo.some(({ empId: empId }) => empId === userId));
    
    console.log(ResultArrayObjOne);
    

提交回复
热议问题