-1

I have two arrays

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

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

I try to find 2,3,4,5 with array.reduce because I think it is more efficient.

Can I do so?

Ahmed Ashour
  • 5,179
  • 10
  • 35
  • 56
Charles Brown
  • 917
  • 2
  • 10
  • 20

2 Answers2

1

This will get you the same result without using 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);

Or with reduce:

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);
gorak
  • 5,233
  • 1
  • 7
  • 19
0

With filter and includes

{
  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)
}
yunzen
  • 32,854
  • 11
  • 73
  • 106