Remove duplicates from an array

“No duplicates”, a Green belt challenge from the CurlyScript Dojo. It uses what Grade 7: Arrays: Lists of Things teaches, and 4 tests check your answer.

The challenge

Write unique(list) that returns a new array with duplicates removed, keeping the first time each item appears.

Example
unique([1, 2, 2, 3, 1])  // [1, 2, 3]

Try it

Write your answer below, then press Check my answer. Your code runs right here in your browser, and the tests tell you what works.

What the tests check

  • unique([1, 2, 2, 3, 1]) gives [1, 2, 3]
  • unique(["a", "b", "a"]) gives ["a", "b"]
  • unique([]) gives []
  • The original array is unchanged: (() => { const input = [1, 1]; unique(input); return input; })() gives [1, 1]

Hints

Stuck? Open one hint at a time. Try again after each one.

Hint 1

Make an empty result array. Push each item only if the result doesn’t includes it yet.

Hint 2

In Grade 13 you’ll learn a one-line trick with Set.

A solution

There’s always more than one right way. Read it, make sure you understand it, then try writing it yourself without looking.

Show one possible solution
Solution
function unique(list) {
  const result = [];
  for (const item of list) {
    if (!result.includes(item)) result.push(item);
  }
  return result;
}

Learn what you need

This exercise uses what Grade 7: Arrays: Lists of Things teaches. Read those notes first if any of it is new.

Practice makes it stick

CurlyScript is a free game that teaches JavaScript from zero: short lessons, an explanation after every answer, and Dojo challenges like this one.

Start learning