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

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

    I prefer map object when it comes to big arrays.

    // create tow arrays
    array1 = Array.from({length: 400},() => ({value:Math.floor(Math.random() * 4000)}))
    array2 = Array.from({length: 400},() => ({value:Math.floor(Math.random() * 4000)}))
    
    // calc diff with some function
    console.time('diff with some');
    results = array2.filter(({ value: id1 }) => array1.some(({ value: id2 }) => id2 === id1));
    console.log('diff results ',results.length)
    console.timeEnd('diff with some');
    
    // calc diff with map object
    console.time('diff with map');
    array1Map = {};
    for(const item1 of array1){
        array1Map[item1.value] = true;
    }
    results = array2.filter(({ value: id2 }) => array1Map[id2]);
    console.log('map results ',results.length)
    console.timeEnd('diff with map');

    0 讨论(0)
  • 2020-11-22 04:55

    I've made a generalized diff that compare 2 objects of any kind and can run a modification handler gist.github.com/bortunac "diff.js" an ex of using :

    old_obj={a:1,b:2,c:[1,2]}
    now_obj={a:2 , c:[1,3,5],d:55}
    

    so property a is modified, b is deleted, c modified, d is added

    var handler=function(type,pointer){
    console.log(type,pointer,this.old.point(pointer)," | ",this.now.point(pointer)); 
    

    }

    now use like

    df=new diff();
    df.analize(now_obj,old_obj);
    df.react(handler);
    

    the console will show

    mdf ["a"]  1 | 2 
    mdf ["c", "1"]  2 | 3 
    add ["c", "2"]  undefined | 5 
    add ["d"]  undefined | 55 
    del ["b"]  2 | undefined 
    
    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2020-11-22 04:57

    Most of answers here are rather complex, but isn't logic behind this quite simple?

    1. check which array is longer and provide it as first parameter (if length is equal, parameters order doesnt matter)
    2. Iterate over array1.
    3. For current iteration element of array1 check if it is present in array2
    4. If it is NOT present, than
    5. Push it to 'difference' array
    const getArraysDifference = (longerArray, array2) => {
      const difference = [];
    
      longerArray.forEach(el1 => {      /*1*/
        el1IsPresentInArr2 = array2.some(el2 => el2.value === el1.value); /*2*/
    
        if (!el1IsPresentInArr2) { /*3*/
          difference.push(el1);    /*4*/
        }
      });
    
      return difference;
    }
    

    O(n^2) complexity.

    0 讨论(0)
  • 2020-11-22 04:58

    You could use Array.prototype.filter() in combination with Array.prototype.some().

    Here is an example (assuming your arrays are stored in the variables result1 and result2):

    //Find values that are in result1 but not in result2
    var uniqueResultOne = result1.filter(function(obj) {
        return !result2.some(function(obj2) {
            return obj.value == obj2.value;
        });
    });
    
    //Find values that are in result2 but not in result1
    var uniqueResultTwo = result2.filter(function(obj) {
        return !result1.some(function(obj2) {
            return obj.value == obj2.value;
        });
    });
    
    //Combine the two arrays of unique entries
    var result = uniqueResultOne.concat(uniqueResultTwo);
    
    0 讨论(0)
  • 2020-11-22 05:02

    If you are willing to use external libraries, You can use _.difference in underscore.js to achieve this. _.difference returns the values from array that are not present in the other arrays.

    _.difference([1,2,3,4,5][1,4,10])
    
    ==>[2,3,5]
    
    0 讨论(0)
提交回复
热议问题