To get all non-unique values in an array with JavaScript, we call the filter
and indexOf
methods.
For instance, we write
const noDups = [1, 2, 2, 4, 3, 4].filter((e, i, a) => a.indexOf(e) !== i);
to call filter
with a callback that checks if a.indexOf
returns an index that’s different from i
.
If this is true
, that means there’s a duplicate of e
since indexOf
returns the first index of e
.