Search code examples
javascriptcollectionsletter

Any equivalent of Java collections in Javascript?


I have to decompose words into collections of letters in Javascript. Then I need to be able to i) check whether a letter belongs to the collection and ii) to remove letters for this collection progressively.

For example, the word 'cool' would be decomposed into 'c', 'o', 'o', 'l'. If I remove 'o', 'a' and 'l', I should be left with 'c', 'o' only.

What is the proper data structure to achieve this in Javascript?


Solution

  • A string!

    var str = 'cool';
    

    To check if a character is in the string:

    if(str.indexOf('o') > -1) // the character is in the string
    

    To remove the first occurrence of a character:

    str = str.replace('o','');
    

    If you want to modify the string object to provide more "logical" representations of these actions you could do this:

    String.prototype.contains = function(char){
        return this.indexOf(char) > -1;
    };
    String.prototype.remove = function(char){
        return this.replace(char,'');
    };
    

    which you could use like this:

    if ('cheese'.contains('che'))
       alert('Velviva!');
    
    var str = 'hurt'.remove('r');   // 'hut'
        str = 'banana'.remove('n'); // 'baana'
        str = 'happy'.remove('c');  // 'happy'