Not sure how do to this, so any help is greatly appreciated
Say I have :
const array1 = [1, 1, 2, 3, 4];
const array2 = [1, 2];
Desired output
const result = [1, 3, 4];
I wish to compare array1
and array2
and for each entry in array2
, remove the equivalent from array1
. So if I have 3 of 1 in array1
and 1 of 1 in array2
, the resulting array should have 2 of 1.
Working on a project that has both jquery and underscore.js if that makes anything easier.
This will run reasonably well. I think its linear time instead of N*N
IMO using
array2
as object instead of array will be most performant way.Here on first find of key we change the value in object so we do not filter that value again as desired in output.
On Side note:- With
object.create
we are creating a object without a prototype so it do not search for values in complete prototype chain.You can try the following. Loop through array1 and check if the element of array2 exists on array1 and splice it out.
You could take a
Map
for counting the items for removing.Not sure the most efficiency way to do this in modern JS, and I'm pretty old-school, so here's an old-school solution:
If you are going to work with large arrays, this solution will perform very well. First convert
array1
to aMap
to make your lookups quick. Then go througharray2
and subtract from yourmap
to signify that the element should get removed. Then finally run through yourmap
and add the keys that have values bigger than0