re: 13 useful JavaScript array tips and tricks you should know VIEW POST


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));
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


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


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

let firstValues = new Set(numOne);

Thanks for pointing that up

Code of Conduct Report abuse