The Set solution is not equivalent due to the filtered result being put through another Set, eliminating duplicates, while the plain filter+includes solution will return duplicates from the first array.
The indexOf solution shouldn't (ab)use an object as a hash map, and then parseInt, really, pretty please. People might copy that code, especially as it is last in your article.
My general purpose solution would be:
/**
* Return elements present in both arrays, without duplicates
*/functionintersectWith(arr,other){constknown=newSet(arr);returnother.filter(function(e){if(!known.has(e)){returnfalse;}known.delete(e);// Avoid duplicates. Remove line if you want duplicates from other.returntrue;});}
I like to avoid the conversation from array to another array (with filter) to a Set and back to array again 😁
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
The Set solution is not equivalent due to the filtered result being put through another Set, eliminating duplicates, while the plain filter+includes solution will return duplicates from the first array.
The
indexOf
solution shouldn't (ab)use an object as a hash map, and thenparseInt
, really, pretty please. People might copy that code, especially as it is last in your article.My general purpose solution would be:
I like to avoid the conversation from array to another array (with filter) to a Set and back to array again 😁