DEV Community

Discussion on: 13 useful JavaScript array tips and tricks you should know

Collapse
 
gabrielpinheiro profile image
Gabriel Pinheiro

Great article!
I love how you mentioned the arr.length = 0;, I've seen obj.arr = []; so many times, messing up references is just a matter of time with the latter.

A nice addition would be to change the 8. Find the intersection of two arrays to do it the other way around as Array.prototype.includes is linear and Set.prototype.has is constant, for larger lists a big difference can be noticed:

let firstValues = [...new Set(numOne)];
let duplicatedValues = numTwo.filter(item => firstValues.has(item));

instead of:

var duplicatedValues = […new Set(numOne)].filter(item => numTwo.includes(item));
Collapse
 
perpetualwar profile image
Srđan Međo

You spread Set into an array, so array won't have has method on it. Small bug on your side.

Collapse
 
gabrielpinheiro profile image
Gabriel Pinheiro

Oh you're right, first line should have been:

let firstValues = new Set(numOne);

Thanks for pointing that up

Collapse
 
andrewbogushevich profile image
Andrew Bogushevich • Edited
numOne = [1, 2]
numTwo = [1, 3, 1]

// original
let duplicatedValues = [new Set(numOne)].filter(item => numTwo.includes(item));
// [1]

// your
let firstValues = new Set(numOne);
duplicatedValues = numTwo.filter(item => firstValues.has(item));
// [1, 1]

to solve this we need either to create second Set or to use includes instead of has