用数组减少[重复]来寻找匹配元素。

问题描述 投票:-2回答:2

我有两个数组

a. [1,2,3,4,5]

b. [2,3,4,5,6]

我试着找2,3,4,5与 array.reduce 因为我认为它是 更有效.

我可以这样做吗?

javascript arrays reduce
2个回答
1
投票

这将使你得到同样的结果,而不需要使用 reduce:

var a=[1,2,3,4,5];
var b= [2,3,4,5,6];

result = a.filter(p=>b.includes(p));

console.log(result);

或与减少。

var a=[1,2,3,4,5];
var b= [2,3,4,5,6];

var result = b.reduce((acc,elem)=>{
    if(a.includes(elem)) acc.push(elem);
    return acc; 
},[]);

console.log(result);

0
投票

filterincludes

{
  const a = [1,2,3,4,5];

  const b = [2,3,4,5,6];
  
  let overlap = a.filter(e => b.includes(e))
  console.log(overlap)
}
© www.soinside.com 2019 - 2024. All rights reserved.