r121
r121

Reputation: 2728

How can I remove duplicate words from a string

I am trying to remove duplicate words from the string that I stored in an object like this.

const myObj = {
  name: "rishi rishi",
  college: "mnit mnit"
};

This is my code to remove duplicate words.

const removeDuplicate = (str) => {
  return [...new Set(str.split(" "))].join(" ");
};

for (const key in myObj) {
  removeDuplicate(myObj[key]);
}

But this code doesn't remove the duplicate word, it just returns the original string.

Anyone, please help me with this.

Upvotes: 0

Views: 220

Answers (1)

DecPK
DecPK

Reputation: 25408

You also have to assign the result of removeDuplicate operation otherwise the changes will be discarded. Since you are creating a change but not storing it in any container i.e. myObj[key]

myObj[key] = removeDuplicate(myObj[key]);

const myObj = {
  name: "rishi rishi",
  college: "mnit mnit",
};

const removeDuplicate = (str) => {
  return [...new Set(str.split(" "))].join(" ");
};

for (const key in myObj) {
  myObj[key] = removeDuplicate(myObj[key]);
}

console.log(myObj);

Upvotes: 3

Related Questions