2017-08-15 13 views
0

我想從數組中刪除特定的字符。 我傳遞一個句子,從該句子的字符應該從阿爾法陣列使用的地圖()和過濾器()去掉,如何使用過濾器和地圖從數組中刪除字符?

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')); 

請讓我知道,我在做什麼錯

+0

請提供所需的輸出。 – trincot

回答

0

內部回調函數不會返回值。 melem!=elem應該是return melem!=elem

經過該校正後,內部filter返回一個數組,其中只有一個字母被刪除,但只有該字母。在外層map的下一次迭代中,您將從頭開始並返回一個僅包含第二個alpha字母的數組,這將爲您提供一個數組數組,其中每個數組中的一個字母字符將被刪除。

然而,你需要一些非常不同的東西:你想要alpha數組中不在字符串中的字符(而不是不在alpha數組中的字符)。

對於您應該應用filteralpha

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'));

0

你也可以由陣列轉換爲字符串使用String#replace並使用句子作爲一個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"));