3

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. Commented 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 Commented Jun 1, 2018 at 19:30

3 Answers 3

7

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"))

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0
function dupRemove(stringValue) {
  let updatedValue = "";
  for (i = 0; i < stringValue.length; i++) {
    if (updatedValue.indexOf(stringValue[i]) == -1) {
      updatedValue = updatedValue + stringValue[i]
    }
  }
  return updatedValue;
}

console.log(dupRemove("apple")); // "aple"

1 Comment

Thank you for contributing to the Stack Overflow community. This may be a correct answer, but it’d be really useful to provide additional explanation of your code so developers can understand your reasoning. This is especially useful for new developers who aren’t as familiar with the syntax or struggling to understand the concepts. Would you kindly edit your answer to include additional details for the benefit of the community?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.