0

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.

r121
  • 2,478
  • 8
  • 25
  • 44

1 Answers1

3

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);
DecPK
  • 24,537
  • 6
  • 26
  • 42