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

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

    JavaScript has Maps, that provide O(1) insertion and lookup time. Therefore this can be solved in O(n) (and not O(n²) as all the other answers do). For that, it is necessary to generate a unique primitive (string / number) key for each object. One could JSON.stringify, but that's quite error prone as the order of elements could influence equality:

     JSON.stringify({ a: 1, b: 2 }) !== JSON.stringify({ b: 2, a: 1 })
    

    Therefore, I'd take a delimiter that does not appear in any of the values and compose a string manually:

    const toHash = value => value.value + "@" + value.display;
    

    Then a Map gets created. When an element exists already in the Map, it gets removed, otherwise it gets added. Therefore only the elements that are included odd times (meaning only once) remain. This will only work if the elements are unique in each array:

    const entries = new Map();
    
    for(const el of [...firstArray, ...secondArray]) {
      const key = toHash(el);
      if(entries.has(key)) {
        entries.delete(key);
      } else {
        entries.set(key, el);
      }
    }
    
    const result = [...entries.values()];
    

    const firstArray = [
        { value: "0", display: "Jamsheer" },
        { value: "1", display: "Muhammed" },
        { value: "2", display: "Ravi" },
        { value: "3", display: "Ajmal" },
        { value: "4", display: "Ryan" }
    ]
    
    const secondArray = [
        { value: "0", display: "Jamsheer" },
        { value: "1", display: "Muhammed" },
        { value: "2", display: "Ravi" },
        { value: "3", display: "Ajmal" },
    ];
    
    const toHash = value => value.value + "@" + value.display;
    
    const entries = new Map();
    
    for(const el of [...firstArray, ...secondArray]) {
      const key = toHash(el);
      if(entries.has(key)) {
        entries.delete(key);
      } else {
        entries.set(key, el);
      }
    }
      
    const result = [...entries.values()];
    
    console.log(result);

提交回复
热议问题