0

I am trying to remove specific characters from an array. I am passing a sentence,characters from that sentence should be removed from alpha array using map() and filters(),

var alpha =['b','c','d','e','f','g','h','a']
            function removeAlpha(sentence){
                return alpha.map(function(melem,mpos,marr){
                    return sentence.toLowerCase().split("").filter(function(elem,pos,arr){
                        melem!=elem
                    });
                }); 
            }

            console.log(removeAlpha('bdog'));

Please let me know ,what i am doing wrong

suchi
  • 83
  • 10

2 Answers2

0

You can also use String#replace by converting the array to a string and use the sentence as a RegExp character set:

var alpha =['b','c','d','e','f','g','h','a'];

function removeAlpha(sentence){
  return alpha
    .join('')
    .replace(new RegExp('[' + sentence + ']', 'g'), '')
    .split(''); // replace all characters with an empty string
}

console.log(removeAlpha("bdog"));
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
0

The inner callback function does not return a value. The melem!=elem should be return melem!=elem

After that correction the inner filter returns an array with one alpha letter removed from it, but only that letter. In the next iteration of the outer map, you start from scratch and return an array with only the second alpha letter removed, etc... This gives you an array of arrays, where in each array one of the alpha characters is removed.

Yet, you need something very different: you want the characters from the alpha array that are not in the sentence (instead of the characters of the sentence that are not in the alpha array).

For that you should apply the filter on alpha:

var alpha =['b','c','d','e','f','g','h','a']
function removeAlpha(sentence){
    return alpha.filter(function(melem){
        return !this.includes(melem);
    }, sentence.toLowerCase());
}

console.log(removeAlpha('bdog'));
trincot
  • 317,000
  • 35
  • 244
  • 286