2

I wrote a code and it works fine, But is there any easy and more handy way to implement that using javascript RegExp Object or any other way ?

function removeDuplicateChar(str) {
	var temp = [], j = 0;
	var arr = str.split("");
	arr.sort();

	for(var i = 0; i < arr.length-1; i++) {
		if(arr[i] != arr[i+1]) {
			temp[j++] = arr[i];
		}
	}
	temp[j++] = arr[arr.length-1];

	for(var i = 0; i < j; i++) {
		arr[i] = temp[i];
	}

	return arr.join("").substring(0,j);
}
console.log(removeDuplicateChar("Rasikawef dfv dd"));

2
  • 1
    const removeDuplicateChar = s => [...new Set(s)].join(""); - note that i didn't pay too much attention to performance, i just made a short alternative.
    – ASDFGerte
    Jun 1, 2018 at 19:29
  • 1
    since it's working fine and you're looking for improvement, i think you should post this in codereview.stackexchange.com
    – Taki
    Jun 1, 2018 at 19:30

2 Answers 2

8

Do you like one liners? Minimal code can be very efficient. Compare the following:

With sets and list comprehension:

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

With reduce:

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

With filter:

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

With map:

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

0
2

let removeDuplicate = (string) => string.split("").reduce((s, c) => {
  if (s) {
    if (-1 == s.indexOf(c)) return s + c;
  }
  return s;
});

console.log(removeDuplicate("banana")); // => ban

console.log(removeDuplicate("Rasikawef dfv dd")); // => Rasikwef dv

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.