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".
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".
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));
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));