w3resource

CoffeeScript function: Extract unique characters from a string

CoffeeScript Function : Exercise-20 with Solution

Write a CoffeeScript function to extract unique characters from a string.

Example string : "thequickbrownfoxjumpsoverthelazydog"
Expected Output : "thequickbrownfxjmpsvlazydg"

Solution :

HTML Code :

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <script src="//jashkenas.github.io/coffee-script/extras/coffee-script.js"></script>
  <title>Extract unique characters from a string</title>
</head>
<body>

</body>
</html>

CoffeeScript Code :


unique_char = (str1) ->
  str = str1
  uniql = ''
  x = 0
  while x < str.length
    if uniql.indexOf(str.charAt(x)) == -1
      uniql += str[x]
    x++
  uniql

console.log unique_char('thequickbrownfoxjumpsoverthelazydog')

Sample Output:

"thequickbrownfxjmpsvlazydg"

Live Demo:

See the Pen coffeescript-exercise-19 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus.