Code Lab

Modo entrevista. Cronômetro de 10 min, sem dicas e sem autocompletar

Remove duplicates from an array

MédiaArrays10 min

Write a function removeDuplicates(values) that returns a new array without duplicates: every value stays once.

  • values is an array of numbers and strings. One array can hold both.
  • Keep the first occurrence of every value, in the original order: [3, 1, 3, 2, 1] gives [3, 1, 2]. Do not sort the result.
  • Two values are the same only when they are strictly equal (===): 1 and '1' are different, 'a' and 'A' are different.
  • An empty array gives [].
  • Return a new array, also when there are no duplicates. Do not change (mutate) the input array.

The interviewer asked you not to use Map or Set. A hidden test checks this rule: there new Map() and new Set() throw an error. The array method includes can tell you if a value is already in the result.

Exemplos

removeDuplicates([3, 1, 3, 2, 1])

Retorna [ 3, 1, 2 ]

removeDuplicates(['b', 'a', 'b'])

Retorna [ 'b', 'a' ]

removeDuplicates([1, '1', 1])

Retorna [ 1, '1' ]

Cobrada em GlobalLogic · Fonte

Carregando o editor...
  1. EntradaremoveDuplicates([ 3, 1, 3, 2, 1 ])
    Esperado[ 3, 1, 2 ]
  2. EntradaremoveDuplicates([ 'b', 'a', 'b' ])
    Esperado[ 'b', 'a' ]
  3. EntradaremoveDuplicates([ 4, 5, 6 ])
    Esperado[ 4, 5, 6 ]

Os testes ocultos rodam no envio