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

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

提交回复
热议问题