Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

263
Visualizações
Best way to remove duplicate sentences from an array of sentences based on their characters, whitespaces inconsequential

Let say we have an array like this

const array = ['bic ycle drive', 'bici ycl frei', 'bicyc le dri ve', 'manace', 'bicycle drive', 'bicycle drive']

I want it to return ['bic ycle drive', 'bici ycl frei', 'manace'] because bic ycle drive, bicyc le dri ve, bicycle drive, bicycle drive are the same sentence with white space in different places.

Summary: Just return unique values, white space is not important.

Ps: We can pick any of the duplicates.

Thank you.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Since ES6 it's easy to create arrays of unique values using a Set, but in this case you need to transform the strings (remove spaces) to find the duplicates, but still preserve the original strings, so you can return them. You can do this by creating a Map with the "string without space" as the key, and the original string as the value. Since Map's keys are unique.

Create a Map by using Array.map() to generate an array of [string without spaces, string]. Then convert the Map.values() iterator back to an array. This will return the last item in each series of duplicates.

const array = ['bic ycle drive', 'bici ycl frei', 'bicyc le dri ve', 'manace', 'bicycle drive', 'bicycle drive']

const result = [...new Map(
  array.map(str => [str.replace(/\s+/g, ''), str])
).values()]

console.log(result)

If you want the first item in a series of duplicates, you can use Array.reduce() to create the Map, and only assign keys if they don't alreay exist:

const array = ['bic ycle drive', 'bici ycl frei', 'bicyc le dri ve', 'manace', 'bicycle drive', 'bicycle drive']

const result = [...array.reduce((acc, str) => {
  const key = str.replace(/\s+/g, '')
  
  return acc.has(key) ? acc : acc.set(key, str)
}, new Map()).values()]

console.log(result)

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda