Find missing element by comparing 2 arrays in Javascript

前端 未结 5 2057
名媛妹妹
名媛妹妹 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:19

    This is my approach(works for duplicate entries too):- //here 2nd argument is actually the current array

    function(previousArray, currentArray) {
        var hashtable=[]; 
    
        //store occurances of elements in 2nd array in hashtable
        for(var i in currentArray){
            if(hashtable[currentArray[i]]){
                hashtable[currentArray[i]]+=1; //add 1 for duplicate letters
            }else{
                hashtable[currentArray[i]]=1; //if not present in hashtable assign 1
            }
        }
        for(var i in previousArray){
                if(hashtable[previousArray[i]]===0 || hashtable[previousArray[i]] === undefined){ //if entry is 0 or undefined(means element not present)
                    return previousArray[i]; //returning the missing element
                }
        else{
                 hashtable[previousArray[i]]-=1; //reduce count by 1
            }
    
        }
    }
    

    Logic is that i have created a blank array called hashtable. We iterate currentArray first and use the elements as index and values as counts starting from 1(this helps in situations when there are duplicate entries). Then we iterate through previousArray and look for indexes, if they match we reduce the value count by 1. If an element of 2nd array doesnt exist at all then our undefined check condition fires and we return it. If duplicates exists, they are decremented by 1 each time and when 0 is encountered, that elment is returned as missing element.

提交回复
热议问题