Categories
JavaScript Answers

How to get all non-unique values in an array with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.