← All tasksJavaScript · Junior

unique: remove duplicates

Write a function unique(array) that returns a new array without repeats, keeping the order of first appearance.

NaN should collapse into one element too, and objects are compared by reference.

Tests (5)

  1. expect(unique([1, 2, 2, 3, 1])).toEqual([1, 2, 3]);
  2. expect(unique(["b", "a", "b"])).toEqual(["b", "a"]);
  3. expect(unique([NaN, NaN, 0, -0])).toEqual([NaN, 0]);
  4. const obj = {};
    expect(unique([obj, obj, {}]).length).toBe(2);
  5. const source = [1, 1];
    unique(source);
    expect(source).toEqual([1, 1]);