代码之家  ›  专栏  ›  技术社区  ›  CodeNoob

使用javascript中具有匹配字符的另一个数组筛选数组

  •  0
  • CodeNoob  · 技术社区  · 2 年前

    是否可以让一个数组过滤另一个与每个字符匹配的数组?

    我有一组日志和一个过滤器,如下所示:

    logs = [{id:1, log: "log1"}], {id:2, log: "log2"}, {id:3, log: "fail"}
    
    filter = ["log"]
    

    它应该会回来

    [{id:1, log: "log1"}, {id:2, log: "log2"}]
    

    如果我的过滤器

    filter = ["1", "fai"]
    

    输出将是

    [{id:1, log: "log1"}, {id:3, log: "fail"]
    
    3 回复  |  直到 2 年前
        1
  •  0
  •   Ele    2 年前

    您可以使用该功能 Array.prototype.filter 以及功能 Array.prototype.some 以便筛选出与筛选器不匹配的对象。

    const match = (filter, key, array) => array.filter(o => filter.some(c => o[key].includes(c))),
          array = [{id:1, log: "log1"}, {id:2, log: "log2"}, {id:3, log: "fail"}];
    
    console.log(match(["log"], "log", array));
    console.log(match(["1", "fai"], "log", array));
        2
  •  0
  •   Kamen Minkov    2 年前

    您可以执行以下操作:

    const logs = [{id:1, log: "log1"}, {id:2, log: "log2"}, {id:3, log: "fail"}]
    const searches = ["1", "fai"]
    const matchingLogs = logs.filter(l => {
        return searches.some(term => l.log.includes(term))
    })
    
        3
  •  0
  •   Gacci    2 年前
    let logs = [{id:1, log: "log1"}, {id:2, log: "log2"}, {id:3, log: "fail"}];
    
    let filter = ["1", "fai"];
    
    /*
     * filter the array using the filter function.  
     * Find any given string in the array of objects.
     * If you have a match, it will be added to the 
     * array that will be returned
     */
    let matches = logs.filter(function(object) {
        return !!filter.find(function(elem) {
            return -1 !== object.log.indexOf(elem);
        });
    });