kingloui
kingloui

Reputation: 161

How do I remove duplicate words in a string in JavaScript?

I've been trying to remove duplicate words from a string, and it's not working.

I have the current string:

const categories = 'mexican, restaurant, mexican, food, restaurant'

and I want this outcome:

const x = 'mexican restaurant food'

I have tried the following:

const x = categories.replace(/,/g, '');

    const uniqueList = x
      .split()
      .filter((currentItem, i, allItems) => {
        return i === allItems.indexOf(currentItem);
      })
      .join();

Which is giving me:

uniqueList = 'chinese restaurant chinese food restaurant'

What is wrong with the code above?

Upvotes: 1

Views: 4298

Answers (5)

Tanmay
Tanmay

Reputation: 1

This Could be done By below code

const categories = 'mexican,restaurant,mexican,food,restaurant'
const x = 'mexican restaurant food'

var a = categories.split(',')
console.log(a)
var b = []
for (i = 0; i < a.length; i++) {
  if (!b.includes(a[i])) {
    b.push(a[i])
  }
}
var c = b.toString()
console.log(c)

Upvotes: 0

Jaied
Jaied

Reputation: 968

This can be done in one single line. Try this code below:

const categories = 'mexican, restaurant, mexican, food, restaurant';
let result = [...new Set(categories.split(", "))].join(" ");

Output: "mexican restaurant food"

The output will be exactly what you want.

Upvotes: 2

Rob Monhemius
Rob Monhemius

Reputation: 5144

const categories = 'mexican, restaurant, mexican, food, restaurant';

    const uniqueList = categories
      .split(', ') // split the string when a comma + space is found
      .filter((currentItem, i, allItems) => {
        return i === allItems.indexOf(currentItem);
      }) // filter out duplicates
      .join(' '); // rejoin array to string
      
 console.log( uniqueList );

Upvotes: 0

Sergei Martianov
Sergei Martianov

Reputation: 301

In String.prototype.split(separator) method, which is used by you, if separator is missed will be returned array with one element - source string. So in your code should be .split(' ') instead of .split(). But better use .split(', ') without const x = categories.replace(/,/g, '');. And even you can .split(/\s*,\s*/), in this way you don't have to care about spaces. Join by default use ',' as separator. So you should write .join(' ').

Upvotes: 0

norbitrial
norbitrial

Reputation: 15166

I like using Set for this kind of purposes. Read in the documentation:

The Set object lets you store unique values of any type, whether primitive values or object references.

This can work for you:

const categories = 'mexican, restaurant, mexican, food, restaurant'.split(', ');

const unique = Array.from(new Set(categories));

console.log(unique);

console.log(unique.join(' '));

I hope that helps!

Upvotes: 1

Related Questions