【问题标题】:Filter array of object from another array从另一个数组中过滤对象数组
【发布时间】:2017-10-26 09:47:13
【问题描述】:

我有两个数组。我想过滤一个包含来自另一个数组的对象的数组。

let array1= [{date:1, count:4}, {date:3, count:6}];
let array2= [1,2,3,4];

过滤这两个数组后,我需要过滤数组如下。

let array= [4,0,6,0];

因此,过滤后的数组包含匹配日期的计数和不匹配值的零。但我只得到匹配的数据。

这是我的代码:

let array = _.map(_.filter(array1, function(o){
    return _.includes(array2, o.date);
}), 'count');

谢谢

【问题讨论】:

    标签: javascript arrays lodash


    【解决方案1】:

    您可以为此使用map()find() 方法。您不需要 filter(),因为对于每个元素,您将返回 count 或 0,因此您可以使用 map()

    let array1= [{date:1, count:4}, {date:3, count:6}];
    let array2= [1,2,3,4];
    
    var array = array2.map(function(e) {
      var f = array1.find(a => a.date == e);
      return f ? f.count : 0
    });
    
    console.log(array)

    【讨论】:

      猜你喜欢
      • 2023-02-03
      • 2019-05-05
      • 2021-05-14
      • 2018-10-03
      • 2020-08-15
      • 1970-01-01
      • 2019-07-18
      相关资源
      最近更新 更多