-1

Given two arrays of unequal length:

var array = [1,2,5,1,2,5,5,3];
var array2 = [2,5,5,3,1,10];

How can I find the values common in both arrays? In this case, output should be "1, 2, 5, 3".

Scheff's Cat
  • 19,528
  • 6
  • 28
  • 56
  • 3
    Please, prevent tag spamming. This is good to collect down-votes only (what you surely do not want). I removed all I found irrelevant. If you do not agree you may [edit] and add some. But, please, add relevant tags only. – Scheff's Cat Sep 19 '18 at 09:17
  • Duplicate of https://stackoverflow.com/questions/1584370/how-to-merge-two-arrays-in-javascript-and-de-duplicate-items – Richard Sep 19 '18 at 09:19
  • You just have to adapt the dupe by filtering out duplicates, like `[...new Set(filteredArray)]` – Luca Kiebel Sep 19 '18 at 09:20

2 Answers2

2

While you like to get unique items of common values, you could use a Set for both arrays and filter the unique values.

This proposal returns a different result as the above duplication target.

function getCommon(a, b) {
    return [...new Set(a)].filter(Set.prototype.has, new Set(b));
}

var a = [1, 2, 5, 1, 2, 5, 5, 3],
    b = [2, 5, 5, 3, 1, 10];
    
console.log(getCommon(a, b));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

In javascript you can use these tow functions

 function intersect(a, b) {
  return a.filter(Set.prototype.has, new Set(b));
}
function removeDuplicates(arr){
    let unique_array = []
    for(let i = 0;i < arr.length; i++){
        if(unique_array.indexOf(arr[i]) == -1){
            unique_array.push(arr[i])
        }
    }
    return unique_array
}
var array1=intersect([1,2,5,1,2,5,5,3], [2,5,5,3,1,10]);
console.log(array1);
console.log(removeDuplicates(array1));
Bilal Ahmed
  • 4,005
  • 3
  • 22
  • 42