-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
  • 4,462
  • 10
  • 33
  • 49
Charles Brown
  • 891
  • 2
  • 9
  • 18

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);
Rajan
  • 4,939
  • 1
  • 5
  • 17
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
  • 31,553
  • 11
  • 69
  • 98