How to remove repeated characters from a string?

Asked

Viewed 2,417 times

2

This is my job:

let longest = (s1, s2) => {
      var s1 = `xyaabbbccccdefww`;
      var s2 = `yestheyarehere`;
      let res2 = s1.concat(s2);


      console.log(res2);

    };
  • Ola @Isa, you have this post on the American stack overflow, it might help you. https://stackoverflow.com/a/19730642/7755215

  • Repeated only in sequence or repeated even in different places of the string?

2 answers

5


Source

Reduce

var s1 = `xyaabbbccccdefww`;
var s2 = `yestheyarehere`;
   let res2 = s1.concat(s2);

const remDup= s=> s.split("").sort().reduce((a,b)=>(a[a.length-1]!=b)?(a+b):a,"")
console.log(remDup(res2))

Filter:

    var s1 = `xyaabbbccccdefww`;
    var s2 = `yestheyarehere`;
       let res2 = s1.concat(s2);

const remDup= s=> s.split("").filter((e,i,f)=>f.indexOf(e)==i).sort().join("")
console.log(remDup(res2))

With map

var s1 = `xyaabbbccccdefww`;
var s2 = `yestheyarehere`;
   let res2 = s1.concat(s2);

const remDup= s=> s.split("").map((c,i,o)=>(o.indexOf(c)==i)?c:"").sort().join("")
console.log(remDup(res2))

You can use the new operator spread javascript with Set to obtain an array of unique values.

The object Set allows you to store unique values of any type

var s1 = `xyaabbbccccdefww`;
var s2 = `yestheyarehere`;
   let res2 = s1.concat(s2);

   const remDup= e => [...new Set(e)].sort().join("");
   console.log(remDup(res2))

 

Spread syntax

Spread Operator basically converts an array into arguments, it is very useful when you need to break an array to pass its values to a function or constructor of an object as separate value arguments. To illustrate in practice, let’s create a simple sum function, which needs 2 arguments as input parameter in its function:

 function soma(a, b) {
     return a + b;
   }

If you intend to use this function you can simply do

 soma(1, 2); // retorna: 3

What if you want to use an array? How to pass 2 values of an array as argument? The most obvious way would be:

 var arr = [1, 2];
 soma(arr[0], arr[1]); // retorna: 3

Is there a more elegant way? There is! You can use soma.apply(null, arr) to invoke that function:

 var arr = [1, 2];
 soma.apply(null, arr); // retorna: 3

With the Spread Operator

 var arr = [1, 2];
 soma(...arr); // retorna: 3
  • Speaking of xurupitas, I’ll start using this variable, will avoid conflicts for sure rs

  • @sam, opa is already >> xurupitas® or xurupitas™

3

Basically the regex you need is this: replace(/(.)(?=.*\1)/g, "")

Your code can look like this:

let longest = (s1, s2) => {
  var s1 = `xyaabbbccccdefww`;
  var s2 = `yestheyarehere`;
  let res2 = s1.concat(s2);
  let str =  res2.replace(/(.)(?=.*\1)/g, "");
  console.log(str);
};

Browser other questions tagged

You are not signed in. Login or sign up in order to post.