【问题标题】:Sort and Filter from an Array in JS在 JS 中对数组进行排序和过滤
【发布时间】:2018-06-21 10:08:30
【问题描述】:

我有以下代码:

var names = ["John Chuck", "Micheal Novak", "john Owen", "Rick John"];
names = _.sortBy( names, function( name ){
        return name;
     }

它给了我一个排序的名字列表。现在,如果我想做一个归档,有可能吗?

就像过滤“约翰”,这样最终列表中只有 3 个名字中包含“约翰”。

【问题讨论】:

    标签: javascript arrays sorting lodash


    【解决方案1】:

    使用Array.prototype.filter()Array.prototype.includes() 尝试以下操作:

    var names = ["John Chuck", "Micheal Novak", "john Owen", "Rick John"];
    names = _.sortBy( names, function( name ){
            return name;
         }).filter(n => n.toLowerCase().includes('john'));
         
    console.log(names)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.core.min.js"></script>

    【讨论】:

      【解决方案2】:

      你可以在javascript中使用.includes

      HTML

      var words = ["John Chuck", "Micheal Novak", "John Owen", "Rick John"];
      
      const result = words.filter(word => word.includes("John"));
      
      console.log(result); //result is: Array ["John Chuck", "John Owen", "Rick John"]
      

      注意: .includes 区分大小写

      【讨论】:

        【解决方案3】:

        不,在您的特定情况下,您不会给出第二个参数,因为您正在对字符串进行排序(除非您想按整个字符串的一部分进行排序......)。

        您需要过滤,然后排序

        【讨论】:

          【解决方案4】:

          由于您使用的是 Lodash.js,您还可以查看 _.reject 函数

          names = _.reject(names, function(name) {
                        return name.match(/[.]*john[.]*/i) == undefined;
                  });
          

          这将只返回 3 个名称。看看-JSFIDDLE DEMO

          【讨论】:

            【解决方案5】:

            一个简单的 ES6 替代方案(没有像 Lodash 这样的库):

            var names = ["John Chuck", "Micheal Novak", "john Owen", "Rick John"];
            
            var result = names.sort((a, b) => a.localeCompare(b)).filter(name => /john/gi.test(name));
            
            console.log(result);
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2020-11-28
              • 1970-01-01
              • 2016-10-30
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2015-10-02
              • 1970-01-01
              相关资源
              最近更新 更多