Find missing element by comparing 2 arrays in Javascript

前端 未结 5 2076
名媛妹妹
名媛妹妹 2020-12-10 06:12

For some reason I\'m having some serious difficulty wrapping my mind around this problem. I need this JS function that accepts 2 arrays, compares the 2, and then returns a s

5条回答
  •  一整个雨季
    2020-12-10 06:14

    This should work. You should also consider the case where the elements of the arrays are actually arrays too. The indexOf might not work as expected then.

    function findDeselectedItem(CurrentArray, PreviousArray) {
    
       var CurrentArrSize = CurrentArray.length;
       var PreviousArrSize = PreviousArray.length;
    
       // loop through previous array
       for(var j = 0; j < PreviousArrSize; j++) {
    
          // look for same thing in new array
          if (CurrentArray.indexOf(PreviousArray[j]) == -1)
             return PreviousArray[j];
    
       }
    
       return null;
    
    }
    

提交回复
热议问题