When merging array of strings, I can use Set
and ES6 to remove duplicates like so:
JavaScript
x
9
1
const a = ["hello", "hi", "yo"]
2
const b = ["alo", "hi"]
3
const remove_hi = [
4
new Set([
5
a,
6
b,
7
]),
8
]
9
But how do I compare and remove objects? Say I have this:
JavaScript
1
17
17
1
const a = [
2
{id: "asd", name: "Hi"},
3
{id: "fgh", name: "Hello"},
4
{id: "123", name: "Hi"}
5
]
6
const b = [
7
{id: "jkl", name: "Yo"},
8
{id: "123", name: "Hi"}
9
]
10
// This will not work. It will have a duplicate of {id: "123", name: "Hi"}
11
const remove_hi = [
12
new Set([
13
a,
14
b,
15
]),
16
]
17
How do I remove {id: "123", name: "Hi"}
from a combined array with Set
?
Advertisement
Answer
Use a Map
to deduplicate by the key name
:
JavaScript
1
18
18
1
const uniqueBy = (array, key) => [
2
new Map(
3
array.map(o => [key(o), o])
4
).values()
5
];
6
7
const a = [
8
{id: "asd", name: "Hi"},
9
{id: "fgh", name: "Hello"},
10
{id: "123", name: "Hi"}
11
]
12
const b = [
13
{id: "jkl", name: "Yo"},
14
{id: "123", name: "Hi"}
15
]
16
const remove_hi = uniqueBy([a, b], o => o.name);
17
18
console.log(remove_hi);
Note that deduplicating only by name
will remove both {id: "asd", name: "Hi"}
and {id: "123", name: "Hi"}
since they’d be considered duplicates of the last {id: "123", name: "Hi"}
in the array when keying by name
.
Replace o.name
with whatever key you want to deduplicate by.