Rasika Weragoda
Rasika Weragoda

Reputation: 984

remove duplicate character in string and make unique string

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

Upvotes: 3

Views: 6364

Answers (3)

Shankar
Shankar

Reputation: 1

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"

Upvotes: 0

Attersson
Attersson

Reputation: 4876

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

Upvotes: 7

Vivek
Vivek

Reputation: 1523

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

Upvotes: 2

Related Questions