JavaScript by Radu TM • June 21, 2022
// Get the intersection of two arrays in JavaScript
// Define a function to get the intersection of two arrays
function getIntersection(arr1, arr2) {
// Use Set constructor to remove duplicates from arr1
let set1 = new Set(arr1);
// Use Set constructor to remove duplicates from arr2
let set2 = new Set(arr2);
// Use the spread operator (...) to convert the set to an array
let intersection = [...set1].filter(x => set2.has(x));
// Return the intersection
return intersection;
}
// Define two arrays
let arr1 = [1, 2, 3, 4, 5];
let arr2 = [3, 4, 5, 6, 7];
// Get the intersection of the two arrays
let intersection = getIntersection(arr1, arr2);
// Print the intersection to the console
console.log(intersection); // [3, 4, 5]
0
21.367
JavaScript by Radu TM • June 21, 2022
// Get the intersection of two arrays in JavaScript
const array1 = ['a', 'b', 'c', 'd'];
const array2 = ['c', 'd', 'e', 'f'];
// Use the Set object to get the unique values
const uniqueValues = new Set([...array1, ...array2]);
// Get the intersection
const intersection = [...uniqueValues].filter(value => array1.includes(value) && array2.includes(value));
console.log(intersection); // Output: ['c', 'd']
0
21.367