Tuesday, May 2, 2017

Functional JavaScript - 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 functiona 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;
Runnable plnkr below. 


Kavi said...

This article is very much helpful and i hope this will be an useful information for the needed one. Keep on updating these kinds of informative things...
Mobile App Development Company
Mobile App Development Company in India
Android app Development Company
ios app development Company
Mobile App Development Companies

Gopi Krishna 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