Tuesday, May 2, 2017

Functional Programming - Finding unique characters in string

These are small code snippets created as part of learning functional JavaScript. As we know when we say functional programming, we have to create pure functions, avoiding assignment etc...It really require practice to write the functional way especially, if we started in imperative languages. This is first in the series where some algorithms are written using functional style.
  1. Functional JavaScript - Finding unique characters in string.

The problem

The problem is simple. Have to find out unique chars in string. eg: Hello has to return Helo. 

Functional ways

The easy way is to loop through the characters and push items into another array, if it is not already present. Finally create string by joining array.

Below is slightly different version where the characters are filtered, if the index found in original string is different than current index.

function uniq(str) {
    return str.split('').filter(function(item, index, self) {
      return self.indexOf(item) == index;
    }).join('');
}
Runnable plnkr below. 

1 comment:

Unknown said...


Just wish to say your article is as astounding. The clearness in your
submit is just excellent and i can suppose you’re knowledgeable in this subject.
Well along with your permission allow me to take hold of your RSS feed to stay up
to date with drawing close post. Thanks a million and
please carry on the rewarding work.
AngularJS Training in Chennai
AngularJS Training Institute in Chennai

AngularJS Certification Training in Chennai