Last active
July 28, 2022 02:28
-
-
Save antoniocsoares/fa794527a0a61f5decd515f502224af7 to your computer and use it in GitHub Desktop.
Find duplicate items in arrays using ES6
This file contains 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
// ES6 | |
// Count duplicate items | |
const names = ['Mike', 'Matt', 'Nancy', 'Adam', 'Jenny', 'Nancy', 'Carl'] | |
const count = names => | |
names.reduce((a, b) => | |
Object.assign(a, {[b]: (a[b] || 0) + 1}), {}) | |
const duplicates = dict => | |
Object.keys(dict).filter((a) => dict[a] > 1) | |
console.log(count(names)) // { Mike: 1, Matt: 1, Nancy: 2, Adam: 1, Jenny: 1, Carl: 1 } | |
console.log(duplicates(count(names))) // [ 'Nancy' ] | |
// Return array with duplicates | |
// prep | |
const arr = Array.from('Learn more javascript dude'); | |
const counter = (prev, next) => Object.assign(prev, { [next] : (prev[next] || 0) + 1 }); | |
const singles = function(key){ return this[key] === 1 }; | |
const multiples = function(key){ return this[key] > 1 }; | |
// work | |
const counted = arr.reduce(counter, {}); | |
const filtered = Object.keys(counted).filter(multiples.bind(counted)); | |
//[ "e", "a", "r", " ", "d" ] | |
console.log(filtered); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
const duplicates = (arr) => {
let seen = new Set();
let store = new Array();
arr.filter(item => seen.size === seen.add(item).size && !store.includes(item) && store.push(item))
return store;
}