从另一个数组过滤对象数组 [英] Filter array of object from another array
本文介绍了从另一个数组过滤对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个数组.我想过滤一个包含另一个数组中对象的数组.
I have two arrays. I want to filter one array which contains objects from another array.
let array1= [{date:1, count:4}, {date:3, count:6}];
let array2= [1,2,3,4];
过滤这两个数组后,我需要如下过滤的数组.
After filtering these two arrays, I need filtered arrays as below.
let array= [4,0,6,0];
因此,过滤后的数组包含匹配日期的计数和不匹配值的零.但我只得到匹配的数据.
So, the filtered array contains the count for matched date and zero for unmatched values. But I'm getting only matched data.
这是我的代码:
let array = _.map(_.filter(array1, function(o){
return _.includes(array2, o.date);
}), 'count');
谢谢
推荐答案
您可以为此使用 map()
和 find()
方法.您不需要 filter()
,因为对于每个元素,您将返回count或0,因此您只需使用 map()
.
You can use map()
and find()
methods for this. You don't need filter()
because for each element you will return count or 0 so you can just use 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)
这篇关于从另一个数组过滤对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文