Scriptdrill

Level 2: Arrays and objects Exercise 12 of 45 Pro

Remove duplicates by a field

A JavaScript exercise from Scriptdrill. Solve it with a code editor in your browser that runs your function against example and hidden tests, and it is checked the moment you submit.

The task

Return the items with duplicates removed, where two items are duplicates when `item[key]` is the same value. Keep the first item for each value, in the original order. Values are compared the way a `Set` compares them, so the number `1` and the string `"1"` are different.

What this exercise teaches

A Set remembers values with their type, so 1 and "1" stay apart, which a plain object used as a lookup would merge. Checking before adding keeps the first occurrence.

A hint if you get stuck

Keep a `Set` of the values you have seen and `filter` the items: keep an item only when its value is not in the set yet.

This exercise is part of Pro

Pro unlocks all 45 exercises, with worked solutions and progress saved to your account. The free exercises work without an account.

You create a free account first, so Pro is attached to it.

Monthly is charged today and then every month until you cancel, in one click from your account page. Lifetime is one payment with no renewals. Full refund within 14 days of paying.

Start with the free exercises

More exercises in Arrays and objects