Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I need to remove every repetitive character from string that given as array

I need to remove every repetitive character from string, all should be good, its working for strings that already given as ‘string’, but if i get array and then transform it to string it didnt work.

function minValue(values){
  values = values.toString("").split(",").join("");
    let result = values.replace(/(.)\1+/g, '$1');
     return result;
}
console.log(minValue([4, 7, 5, 7]));

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

As it is not clear enough, if the Value will be a string or an Array, i’ve added a guarding if statement, that converts possible strings to an array.

function minValue(values){
  // If you get a string, you'll need to split this into an array
  if(typeof values === "string") values = values.split("");
  
  // A set only accepts distinct values and we can create a new 
  // set by providing an array as a base.
  // We then create a new Array by using the Array.from() mothod, 
  // which can use an array-like structure, to create a new array.
  // This way, we remove any duplicate value from an array and 
  // return the result as a string, by joining all items together.
  return Array.from(new Set(values)).join("");
}

console.log(minValue([4, 7, 5, 7]));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading