1

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
  • 725
  • 3
  • 14
  • 36

4 Answers4

2

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

gtournie
  • 4,143
  • 1
  • 21
  • 22
2

Like this:

'javascript'.split('').filter(function(value, index, self) { 
   return self.indexOf(value) === index;
 })
CD..
  • 72,281
  • 25
  • 154
  • 163
  • No, it will produce an array like this : ["j", "a", "v", "a", "s", "c", "r", "i", "p", "t"] I only want need one "a". – ishwr Dec 19 '13 at 10:49
  • @catwoman: This one works well. Result is: ["j", "a", "v", "s", "c", "r", "i", "p", "t"] – Synthetx Dec 19 '13 at 10:54
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,890
  • 3
  • 22
  • 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,290
  • 1
  • 19
  • 22