Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

261
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!