Find missing element by comparing 2 arrays in Javascript

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

    Problem statement:

    Find the element that is missing in the currentArray that was there in the previous array.

    previousArray.filter(function(x) {  // return elements in previousArray matching...
        return !currentArray.includes(x);  // "this element doesn't exist in currentArray"
    })
    

    (This is as bad as writing two nested for-loops, i.e. O(N2) time. This can be made more efficient if necessary, by creating a temporary object out of currentArray, and using it as a hashtable for O(1) queries. For example:)

    var inCurrent={}; currentArray.forEach(function(x){ inCurrent[x]=true });
    

    So then we have a temporary lookup table, e.g.

    previousArray = [1,2,3]
    currentArray = [2,3];
    inCurrent == {2:true, 3:true};
    

    Then the function doesn't need to repeatedly search the currentArray every time which would be an O(N) substep; it can instantly check whether it's in currentArray in O(1) time. Since .filter is called N times, this results in an O(N) rather than O(N2) total time:

    previousArray.filter(function(x) {
        return !inCurrent[x]
    })
    

    Alternatively, here it is for-loop style:

    var inCurrent = {};
    var removedElements = []
    for(let x of currentArray)
        inCurrent[x] = true;
    for(let x of previousArray)
        if(!inCurrent[x])
            removedElements.push(x)
            //break; // alternatively just break if exactly one missing element
    console.log(`the missing elements are ${removedElements}`)
    

    Or just use modern data structures, which make the code much more obvious:

    var currentSet = new Set(currentArray);
    return previousArray.filter(x => !currentSet.has(x))
    

提交回复
热议问题