Jump to the editorJAVASCRIPT
JAVASCRIPT JAVASCRIPT JAVASCRIPT
4.7. Remove duplicates (values and by key)
Easy
Topics
This question is in
4. Array utilitiesA list of tags typed by users has "css" three times. Merging two pages of search results repeats the products that were on both pages. A list of recent files should show each file once, keeping the most recent position. Removing duplicates is one of the most common array tasks, and the details matter: which copy is kept, what counts as "the same", and whether it stays fast for long lists.
Write uniq(array), which keeps each value once, and uniqBy(array, iteratee), which keeps the first item for each key, in uniq.js.
Signature
function uniq(array) // returns a new array
function uniqBy(array, iteratee) // returns a new arrayiterateegives each item's key: a function, called asiteratee(item), or a property name such as"id", which meansitem.id.- Both return a new array of items from
array, in the order they first appeared.arrayis not changed.
Requirements
uniqkeeps the first occurrence of each value, in the order of first appearance.- Values are compared the way a
Setcompares them:NaNmatchesNaN,0matches-0, and nothing else is converted (1and"1"are different). - Of
0and-0, the one that comes first is kept as it was. - Objects match only when they are the same object, not when they look alike.
undefinedandnullare kept once each. A hole counts asundefined.- An empty array gives
[]. The result is always a new array, and the input is not changed. uniqBykeeps the first item for each key and returns the items, not the keys.uniqByaccepts a function or a property name, and calls the iteratee once per item, with the item.uniqBycompares keys the same wayuniqcompares values.- Both handle 100,000 items quickly.
Examples
uniq([3, 1, 3, 2, 1]); // [3, 1, 2]
uniq([NaN, 1, NaN, "1"]); // [NaN, 1, "1"]uniqBy([2.1, 1.2, 2.3], Math.floor); // [2.1, 1.2]
uniqBy([{ id: 1, v: "a" }, { id: 2, v: "b" }, { id: 1, v: "c" }], "id");
// [{ id: 1, v: "a" }, { id: 2, v: "b" }]uniq([{ a: 1 }, { a: 1 }]); // both kept: two different objects
uniq([]); // []Environment
- Plain JavaScript in a browser page; the tests call the globals
uniqanduniqByfromuniq.js. - Any built-in may be used.
- One test runs both functions on 100,000 different values and expects them to finish in well under a second.
Hints
- Checking "have I seen this?" by searching the result array gets slower as the result grows. What remembers values with a fast lookup?
- A
Setstores-0as0. If you build the result from the Set, which value comes out?
The explanation comes with the course
A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.
- Every line explained
- The mistakes each test catches
- Links to the lessons behind it
Back to the question
Loading the editor…