I need to check a JavaScript array to see if there are any duplicate values. What\'s the easiest way to do this? I just need to find what the duplicated values are - I don\'
UPDATED: Short one-liner to get the duplicates:
[1, 2, 2, 4, 3, 4].filter((e, i, a) => a.indexOf(e) !== i) // [2, 4]
To get the array without duplicates simply invert the condition:
[1, 2, 2, 4, 3, 4].filter((e, i, a) => a.indexOf(e) === i) // [1, 2, 3, 4]
I simply did not think about filter()
in my old answer below ;)
When all you need is to check that there are no duplicates as asked in this question you can use the every()
method:
[1, 2, 3].every((e, i, a) => a.indexOf(e) === i) // true
[1, 2, 1].every((e, i, a) => a.indexOf(e) === i) // false
Note that every()
doesn't work for IE 8 and below.