javascript string de-duplication

String Reduplication Method

Method 1: Set

Because the Set structure is characterized by no duplicate elements.

let str = [...new Set('abcabcabcabc')].join('')
console.log(str)
VM904:2 abc

Method 2: for cycle

function noRepeat(str){
  let s = "";
  let flag;
  let len = str.length;
  for (let i=0;i<len;i++) {
    flag=1;
    let slen = s.length
    for (let j=0;j<slen;j++) {
      if(str[i]===s[j]) {
        flag=0;
        break;
      }
    }
    if (flag) {
      s+=str[i];
    }
  }
  return s;
}
let ss = "abcabcabcabcd";
let tem = noRepeat(ss);
console.log(tem);
//Operation results:
VM955:22 abcd

Method 3: search()

function noRepeat(str){
  let s = "";
  let len = str.length;
  for(let i=0;i<len;i++){
    if(s.search(str[i])===-1){
      s+=str[i]
    }
  }
  return s;
}
let ss = "abcabcabcabcd";
let tem = noRepeat(ss);
console.log(tem);
//Operation results:
VM193:13 abcd

Method 4: indexOf

function noRepeat(str){
  let s = "";
  let len = str.length;
  for(let i=0;i<len;i++){
    if(s.indexOf(str[i])==-1){
      s+=str[i]
    }
  }
  return s;
}
let ss = "abcabcabcabcd";
let tem = noRepeat(ss);
console.log(tem);
//Operation results:
VM263:13 abcd

Method 5: Object attributes

function noRepeat(str){
  let s = "";
  let obj = {};
  let len = str.length;
  for(let i=0;i<len;i++){
    if(!obj[str[i]]){
      s+=str[i]
      obj[str[i]]=1
    }
  }
  return s;
}
let ss = "abcabcabcabcd";
let tem = noRepeat(ss);
console.log(tem);
//Operation results:
VM415:15 abcd

Method 6: include ()

function noRepeat(str){
  let s = "";
  let len = str.length;
  for(let i=0;i<len;i++){
    if(!s.includes(str[i])){
      s+=str[i]
    }
  }
  return s;
}
let ss = "abcabcabcabcd";
let tem = noRepeat(ss);
console.log(tem);
//Operation results:
VM842:13 abcd

Method 7: filter()

Principle: indexOf always returns the location of the first element, and the location of subsequent duplicate elements is not equal to the location returned by indexOf, so it is filtered out by filter, so the de duplication is realized.

let tem = [].filter.call("abcdefasfjklbbbaaa", (curr,i,str) => str.indexOf(curr)==i).join('');
console.log(tem);
//Operation results:
VM1189:2 abcdefsjkl

Posted by DrDre on Fri, 04 Oct 2019 23:53:20 -0700