← 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.
Ctrl+Enter runs the tests. Tab indents; to leave the editor with the keyboard, press Esc and then Tab. Your code is saved in this browser.
Tests (5)
expect(unique([1, 2, 2, 3, 1])).toEqual([1, 2, 3]);
expect(unique(["b", "a", "b"])).toEqual(["b", "a"]);
expect(unique([NaN, NaN, 0, -0])).toEqual([NaN, 0]);
const obj = {}; expect(unique([obj, obj, {}]).length).toBe(2);
const source = [1, 1]; unique(source); expect(source).toEqual([1, 1]);