Example:

arr1 [1,2,3,4,5,8,11,16,19] arr2 [90,54,34,12,1,2,3,4,5,7,82] 

Must return:

 arr3 [1,2,3,4,5] 

And yet, how to return an array of ordinal numbers of these values ​​in the first array? That is, return the array

 arr4[0, 1, 2, 3, 4] 
  • You can compare them using 2 cycles. An example is this link - x_ror

1 answer 1

You can use the Array.prototype.filter method:

 var arr1 = [1, 2, 3, 4, 5, 8, 11, 16, 19]; var arr2 = [90, 54, 34, 12, 1, 2, 3, 4, 5, 7, 82]; var arr3 = arr1.filter(function(n){ return arr2.indexOf(n) >= 0; }); console.info(arr3); 

And you can solve the problem "in the forehead":

 var arr1 = [1, 2, 3, 4, 5, 8, 11, 16, 19]; var arr2 = [90, 54, 34, 12, 1, 2, 3, 4, 5, 7, 82]; function intersection(arr1, arr2) { if (arr1.length <= arr2.length) { var result = []; for (var i = 0; i < arr1.length; ++i) for (var j = 0; j < arr2.length; ++j) if (arr1[i] == arr2[j]) { result.push(arr1[i]); break; } return result; } return intersection(arr2, arr1); } console.info(intersection(arr1, arr2)); 

  • one
    And can the existing library, for example lodash.com/docs/4.17.4#intersection - Alexey Ten
  • one
    The first can be written shorter (but less cross-browser) var arr3 = arr1.filter(n=>arr2.includes(n)); - Alexey Ten
  • And how to return an array of ordinal numbers of these values ​​in the first array? That is: arr1 - [1, 2, 3, 4, 6, 8, 90, 67] arr2 - [5, 17, 54, 1, 2, 3, 4, 6, 8, 90, 67] Return an array [0, 1, 2, 3, 4, 5] - Kristina Kuli
  • @KristinaKuli In the second variant, remove the length check, recursive intersection call and replace result.push(arr1[i]) with result.push(i) . - user194374