1
  1. with some

function test(arr1,arr2){
  return arr1.filter(el1=>{
    return arr2.some(el2=>{
      return el2 === el1
    })
  })
}

console.log(test([1,2,3,4],[3,4,5,6]))
  1. with includes

function test(arr1,arr2){
  return arr1.filter(item => arr2.includes(item));
}
    
console.log(test([1,2,3,4],[3,4,5,6]))

Maybe there are better way to solve this task?

Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
Alex
  • 11
  • 1
  • 1
    They have the same complexity. They are of equivalent goodness. – James Jan 02 '21 at 11:46
  • If these arrays were large, I would suggest using Set's. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set – Keith Jan 02 '21 at 11:48
  • These both have `O(n*m)` complexity, but `O(n+m)` is achievable – Bergi Jan 02 '21 at 12:28

2 Answers2

0

A better way would be using a Set to save the numbers in the first array.

Then, iterate over the second array using .forEach and add each item that is in the set:

function getIntersection(arr1 = [], arr2 = []) {
  const set = new Set(arr1);
  const intersection = [];
  arr2.forEach(num => {
    if(set.has(num)) intersection.push(num);
  });
  return intersection;
}

console.log( getIntersection([1,2,3,4], [3,4,5,6]) );
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
0

You could take a Set for one array and filter the other one.

Basically you need one loop for every array.

function test(arr1, arr2) {
    return arr1.filter(Set.prototype.has, new Set(arr2));
}

console.log(test([1, 2, 3, 4], [3, 4, 5, 6]))
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392