Created
February 12, 2019 17:37
-
-
Save tonyjcamp/69bca3a96d52f9c606f026c4bf8ce3e1 to your computer and use it in GitHub Desktop.
Return duplicate values in an Array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const names = ['Mike', 'Matt', 'Nancy', 'Adam', 'Jenny', 'Nancy', 'Carl', 'Nancy', 'Carl'] | |
const uniq = names | |
.map((name) => { | |
return {count: 1, name: name} | |
}) | |
.reduce((a, b) => { | |
a[b.name] = (a[b.name] || 0) + b.count | |
return a | |
}, {}) | |
const duplicates = Object.keys(uniq).filter((a) => uniq[a] > 1) | |
console.log(duplicates) // [ 'Nancy', 'Carl' ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
console.log(a, b, b.count, a[b.name])
// {Mike: 1} {count: 1, name: "Mike"} 1 1
// {Mike: 1, Matt: 1} {count: 1, name: "Matt"} 1 1
// {Mike: 1, Matt: 1, Nancy: 1} {count: 1, name: "Nancy"} 1 1
// {Mike: 1, Matt: 1, Nancy: 1, Adam: 1} {count: 1, name: "Adam"} 1 1
// {Mike: 1, Matt: 1, Nancy: 1, Adam: 1, Jenny: 1} {count: 1, name: "Jenny"} 1 1
// {Mike: 1, Matt: 1, Nancy: 2, Adam: 1, Jenny: 1} {count: 1, name: "Nancy"} 1 2
// {Mike: 1, Matt: 1, Nancy: 2, Adam: 1, Jenny: 1, …} {count: 1, name: "Carl"} 1 1
// {Mike: 1, Matt: 1, Nancy: 3, Adam: 1, Jenny: 1, …} {count: 1, name: "Nancy"} 1 3
// {Mike: 1, Matt: 1, Nancy: 3, Adam: 1, Jenny: 1, …} {count: 1, name: "Carl"} 1 2