0

I think the title is self explanatory. Is it possible to only push the unique char from a string into the array using split() methode? Example : from string "javascript", I want an output array to be :

["j", "a", "v", "s", "c", "r", "i", "p", "t"]

Thank you!

ishwr
  • 695
  • 2
  • 13
  • 36

4 Answers4

2

'javascript'.split('') => ['j', 'a', 'v', 'a', 's', 'c', 'r', 'i', 'p', 't']

gtournie
  • 3,774
  • 1
  • 19
  • 22
1

Like this:

'javascript'.split('').filter(function(value, index, self) { 
   return self.indexOf(value) === index;
 })
CD..
  • 68,981
  • 24
  • 147
  • 156
1

Something like this?

var string = 'javascript';
var uniqueArr = [];
string.split('').forEach(function(e, i) {
    if (uniqueArr.indexOf(e) == -1) {
        uniqueArr.push(e)
    }
});

uniqueArr would contain all your 'unique char's

tewathia
  • 6,380
  • 3
  • 21
  • 27
1

Use a hash array to remember chars have appeared.

function unqArr(str) {

    //char flag hash
    var unqHash = {};

    return str.split('').filter(function(c) {

        //this char has appeared
        if (unqHash[c])
            return false;

        //flag this char
        unqHash[c] = 1;
        return true;
    });
}

http://jsfiddle.net/rooseve/s92Jm/

Andrew
  • 5,228
  • 1
  • 16
  • 22