Created
December 5, 2019 14:17
-
-
Save ahmehri/fc04baf3f83017deaba24cb3f446456d to your computer and use it in GitHub Desktop.
How to find duplicates 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
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