Unique ArrayLoading saved progress…

Unique Array

You're asked to deduplicate. Implement uniqueArray(arr): return a new array that contains each value from arr exactly once, in the order each value first appeared. Don't mutate the input; don't reorder things.

This is the same job as wrapping an array with new Set(...) and reading the result back out. You can use a Set, or roll your own bookkeeping — either way the contract is what matters.

Signature

function uniqueArray(arr) {
  // returns a new array containing the distinct values of `arr`,
  // in the order each value first appeared.
}

Examples

uniqueArray([1, 2, 2, 3, 1, 4]);         // [1, 2, 3, 4]
uniqueArray(['a', 'b', 'a', 'c', 'b']);  // ['a', 'b', 'c']
uniqueArray([]);                  // []
uniqueArray([NaN, NaN, 1, NaN]);  // [NaN, 1]   — NaN counts as equal to NaN
uniqueArray([{ a: 1 }, { a: 1 }]); // both kept — objects compare by reference

Notes

  • Preserve insertion order — the first occurrence of each value stays where it was; later duplicates drop out.
  • Equality is SameValueZero — the same rule Set and Array.prototype.includes use. NaN equals NaN, and -0 equals 0.
  • Reference equality for objects — two distinct object literals with the same keys are not duplicates of each other; only the same object reference is.
  • Don't mutate the input — return a new array. The caller's array stays untouched.
  • Empty input — return [], not undefined.
Loading editor…