Skip to content
Advertisement

Remove duplicates from a string by value

function removeDuplicateCharacters(string) {
  return string
    .split('')
    .filter(function(item, pos, self) {
      return self.indexOf(item) == pos;
    })
    .join('');
}
console.log(removeDuplicateCharacters('baraban'));

I have a JS function which removes duplicates in string. I want to add a duplicate limit to function paremeter. In example if removeDuplicateChracters(“hellomellotesto”, 2 ) expected output should be “hellomeotst”.

Advertisement

Answer

You can try like this:

function removeDuplicateCharacters(string, limit) {
  const ref = {}

  return string
    .split('')
    .filter(function(item, pos) {
      ref[item] = (ref[item] || 0) + 1;

      return ref[item] <= limit;
    })
    .join('');
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement