Skip to content

Instantly share code, notes, and snippets.

@clohr
Created March 4, 2017 19:56
Show Gist options
  • Select an option

  • Save clohr/ebbfdbb3ae1b43711d9867a31a65a36f to your computer and use it in GitHub Desktop.

Select an option

Save clohr/ebbfdbb3ae1b43711d9867a31a65a36f to your computer and use it in GitHub Desktop.
Return duplicates within a JS array
const count = names => names.reduce((acc, name) => Object.assign(acc, {[name]: (acc[name] || 0) + 1}), {})
const duplicates = dict => Object.keys(dict).filter((a) => dict[a] > 1)
const getDuplicates = vals => duplicates(count(vals))
export default getDuplicates
@clohr
Copy link
Copy Markdown
Author

clohr commented Mar 4, 2017

Alternate version:

const getDupes = (arr) => {
  const data = arr.join('')
  const dupes = arr.filter(val => data.match(new RegExp(val, 'gi')).length > 1)
  const uniqueValues = new Set(dupes)
  return [...uniqueValues]
}
export default getDupes

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment