【问题标题】:how to remove character from array using filters and map?如何使用过滤器和映射从数组中删除字符?
【发布时间】:2017-08-15 15:03:27
【问题描述】:

我正在尝试从数组中删除特定字符。 我正在传递一个句子,应该使用 map() 和 filters() 从 alpha 数组中删除该句子中的字符,

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

请告诉我,我做错了什么

【问题讨论】:

  • 请提供所需的输出。

标签: ecmascript-6 es6-map


【解决方案1】:

内部回调函数不返回值。 melem!=elem 应该是 return melem!=elem

在更正之后,内部filter 返回一个数组,其中删除了一个字母,但只有那个字母。在外部map 的下一次迭代中,您从头开始并返回一个仅删除第二个字母的数组,等等...这为您提供了一个数组数组,其中每个数组中的一个字母字符被删除.

然而,您需要一些非常不同的东西:您需要 alpha 数组中不在句子中的字符(而不是句子中不在 alpha 数组中的字符)。

为此,您应该在alpha 上应用filter

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

【讨论】:

    【解决方案2】:

    您也可以通过将数组转换为字符串来使用String#replace,并将句子用作正则表达式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"));

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-14
      • 2021-06-05
      • 2022-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-02
      • 2017-11-13
      相关资源
      最近更新 更多