Notes

JavaScript - Finding duplicate values in an array

author: Paul Kim

categories: js

tags: js

Finding duplicate values in an array

There are so many ways to ask this question and so many different answers:

  • Check if array contains duplicate values. Returns true if it does, false otherwise.
  • Return an array of all duplicated items (i.e., [1, 1, 1] returns [1, 1] since it is duplicated twice)
  • Return an array of unique duplicated items (i.e., [1, 1, 1] returns [1] instead of [1, 1])
  • Return unique values only from duplicate array (i.e., [1, 1, 2] returns [1, 2])
var arr = [9, 9, 9, 111, 2, 3, 3, 3, 4, 4, 5, 7]

// returns boolean to indicate whether or not array contains duplicates
var containsDupes = new Set(arr).size !== arr.length
console.log(containsDupes)

// O(n) solution using indexOf
// return all duplicated items
var filtered = arr.filter((el, index) => arr.indexOf(el) !== index)
console.log(filtered)

// return all duplicated items (unique values only)
var duplicates = [...new Set(filtered)]
console.log(duplicates)

// O(n) solution using indexOf
// return array with unique values only (filter out duplicates)
var results = arr.filter((el, index) => arr.indexOf(el) === index)
console.log(results)

// O(1) solution
// return all duplicated items (unique values only)
var dupes = arr.filter(((t = {}), (e) => !(1 - (t[e] = ++t[e] | 0))))
console.log(dupes)

// O(1) solution
// return array with unique values only (filter out duplicates)
var uniques = arr.filter(((t = {}), (e) => !(1 - (t[e] = ++t[e] | 1))))
console.log(uniques)

Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array Get all unique values in a JavaScript array (remove duplicates)


ChromeEdgeFirefoxOpera

© 2021 paulkode.com. All rights reserved.