Skip to content

Instantly share code, notes, and snippets.

@antoniocsoares
Last active July 28, 2022 02:28
Show Gist options
  • Save antoniocsoares/fa794527a0a61f5decd515f502224af7 to your computer and use it in GitHub Desktop.
Save antoniocsoares/fa794527a0a61f5decd515f502224af7 to your computer and use it in GitHub Desktop.
Find duplicate items in arrays using ES6
// 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);
@TNT-RoX
Copy link

TNT-RoX commented Feb 23, 2018

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;
}

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