Skip to content

Instantly share code, notes, and snippets.

@LaloHao
Created January 30, 2019 21:47
Show Gist options
  • Save LaloHao/89983d454d811de75373315a568697c7 to your computer and use it in GitHub Desktop.
Save LaloHao/89983d454d811de75373315a568697c7 to your computer and use it in GitHub Desktop.
Return an array of `keys` for which their `value` in `object` are duplicates
// Return an array of `keys` for which their `value` in `object` are duplicates
function duplicates(object) {
const keys = Object.keys(object);
const values = keys.map(k => object[k]);
const arr = keys.map(key => ({ key, value: object[key] }));
const _duplicates = new Set();
let possibleDuplicate;
for (const v of values) {
possibleDuplicate = arr.filter(a => a.value === v);
if (possibleDuplicate && possibleDuplicate.length > 1) {
possibleDuplicate = possibleDuplicate.forEach(d => _duplicates.add(d.key));
}
}
return Array.from(_duplicates);
}
@LaloHao
Copy link
Author

LaloHao commented Jan 30, 2019

Example

duplicates({
 x: 1,
 y: 2,
 z: 1,
 xx: 1,
 L: 0,
});

yields

=> [ 'x', 'z', 'xx' ]

@LaloHao
Copy link
Author

LaloHao commented Feb 1, 2019

With lodash

Array.from(new Set(Object.values(_.groupBy(Object.entries({
 x: 1,
 y: 2,
 z: 1,
 xx: 1,
 L: 0,
}), i => i[1])).filter(a => a.length > 1).flat().map(a => a[0])))

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