[英]Filter array in Typescript using functional programing [filter, map, some, reduce etc]
I'm trying to work with functional programming我正在尝试使用函数式编程
I have two arrays我有两个数组
arr1=[{prodId:2}{prodId:4}]
arr2=[{id:1, name:"Test1"},
{id:2, name:"Test2"},
{id:3, name:"Test3"},
{id:4, name:"Test4"},
{id:5, name:"Test5"}]
using a combination of使用组合
filter, map, some, reduce functions
过滤器,映射,一些,减少功能
I want to extract items from arr2我想从 arr2 中提取项目
where arr2.id === arr1.prodId
my output arr would be:我的输出 arr 将是:
[{id:2, name:"Test2"},
{id:4, name:"Test4"}]
I'm trying to avoid forEach and use functional programming.我试图避免 forEach 并使用函数式编程。
You should use filter
method in combination with includes
and map
.您应该将
filter
方法与includes
和map
结合使用。
let arr1=[{prodId:2},{prodId:4}], arr2=[{id:1, name:"Test1"}, {id:2, name:"Test2"}, {id:3, name:"Test3"}, {id:4, name:"Test4"}, {id:5, name:"Test5"}]; let ids = arr1.map(({prodId}) => prodId); let result = arr2.filter(({id}) => ids.includes(id)); console.log(result);
Another approach is to use some
method.另一种方法是使用
some
方法。
let arr1=[{prodId:2},{prodId:4}], arr2=[{id:1, name:"Test1"}, {id:2, name:"Test2"}, {id:3, name:"Test3"}, {id:4, name:"Test4"}, {id:5, name:"Test5"}]; let result = arr2.filter(({id}) => arr1.some(({prodId}) => prodId == id)); console.log(result);
Solutions using .includes
, .find
, or .some
are array operations and cost linear time.使用
.includes
、 .find
或.some
解决方案是数组操作和成本线性时间。 When used inside .filter
, another linear time operation, the result is a quadratic time computation.当在
.filter
,另一个线性时间运算,结果是二次时间计算。 If the input lists are large, this impact is not insignificant.如果输入列表很大,则这种影响并非微不足道。
Instead, first collect the ids to match in a Set then take advantage of constant time lookup in the filter
-相反,首先收集要在 Set 中匹配的 id,然后利用
filter
的恒定时间查找 -
const arr1 = [ { prodId: 2 } , { prodId: 4 } ] const arr2 = [ { id:1, name:"Test1" } , { id:2, name:"Test2" } , { id:3, name:"Test3" } , { id:4, name:"Test4" } , { id:5, name:"Test5" } ] const find = (whitelist, list) => { const ids = new Set (whitelist.map(x => x.prodId)) // create a set return list.filter(x => ids.has(x.id)) // Set#has uses constant time } console.log(find(arr1,arr2)) // [ { id: 2, name: "Test2" }, { id: 4, name: "Test4" } ]
Is this what you are looking for.这是你想要的。
arr1=[{prodId:2},{prodId:4}] arr2=[{id:1, name:"Test1"}, {id:2, name:"Test2"}, {id:3, name:"Test3"}, {id:4, name:"Test4"}, {id:5, name:"Test5"}] let k=arr2.reduce((o,a)=>{ if(arr1.map(a=>a.prodId).indexOf(a.id)!=-1) { o.push(a) } return o; },[]) console.log(k)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.