Skip to content

Instantly share code, notes, and snippets.

@ahmehri
Created December 5, 2019 14:17
Show Gist options
  • Save ahmehri/fc04baf3f83017deaba24cb3f446456d to your computer and use it in GitHub Desktop.
Save ahmehri/fc04baf3f83017deaba24cb3f446456d to your computer and use it in GitHub Desktop.
How to find duplicates in an array
import groupBy from 'lodash.groupby';
// How to find duplicates, e.g in this example by "label"
// from
// [
// { label: "brand", key: "1" },
// { label: "brand", key: "2" },
// { label: "state", key: "3" }
// { label: "state", key: "4" },
// { label: "uniq", key: "5" },
// ]
// to
// [
// { label: "brand", key: "1" },
// { label: "brand", key: "2" },
// { label: "state", key: "3" }
// { label: "state", key: "4" },
// ]
const items = [
{ label: "brand", key: "1" },
{ label: "brand", key: "2" },
{ label: "state", key: "3" },
{ label: "state", key: "4" },
{ label: "uniq", key: "5" },
];
const itemsByLabel = groupBy(items, 'label');
const duplicatedItems = Object.values(itemsByLabel)
.filter(group => group.length > 1)
.reduce((acc, group) => [...acc, ...group])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment