Description of the problem:
Find the element that is not in the current array 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 just as bad as writing two nested for loops, i.e. O (N 2 ). This can be made more efficient, if necessary, by creating a temporary object from currentArray , and using it as a hash table for O ( 1) requests. For example :)
var inCurrent={}; currentArray.forEach(function(x){ inCurrent[x]=true });
So, we have a temporary search table, for example.
previousArray = [1,2,3] currentArray = [2,3]; inCurrent == {2:true, 3:true};
Then the function does not need to repeatedly search for the current Array each time, which would be the O (N) approach; it can instantly check if it is in currentArray O (1) times. Since .filter is called N times, this results in a total time of O (N), not O (N 2 ):
previousArray.filter(function(x) { return !inCurrent[x] })
Alternatively, here is the style for the loop:
var inCurrent = {}; var removedElements = [] for(let x of currentArray) inCurrent[x] = true; for(let x of previousArray) if(!inCurrent[x]) removedElements.push(x)
Or just use modern data structures that make the code more obvious:
var currentSet = new Set(currentArray); return previousArray.filter(x => !currentSet.has(x))