How to use Set Intersection In Javascript

This method involves comparing sets to find common elements among rows in a matrix. It’s a straightforward method that simplifies the process of identifying shared elements efficiently.

Example: To demonsrtate finding the common elements in all rows of agiven matrix using JavaScript set intersection method.

JavaScript
function findCommonElements(matrix)
 {
    if (matrix.length === 0) return [];

    // Convert first row to set
    let commonSet = new Set(matrix[0]);

    // Intersect with sets of subsequent rows
    for (let i = 1; i < matrix.length; i++) 
    {
        commonSet = new Set(matrix[i]
            .filter(x => commonSet.has(x)));
    }

    return Array
        .from(commonSet);
}

const matrix1 = [
    [1, 2, 3],
    [2, 3, 4],
    [3, 4, 5]
];


console.log(findCommonElements(matrix1));
const matrix2 = 
[
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];
console.log(findCommonElements(matrix2));

Output
[ 3 ]
[]

Time Complexity: O(n*m), where n is the number of rows and m is the average number of elements in each row.

Space Complexity: O(m), where m is the average number of elements in each row.

Find Common Elements in all Rows of a Given Matrix using JavaScript

Matrix manipulation takes place in a large number of applications, and the detection of shared elements among rows is one of the common challenges.

Example:

Input :  [1, 2, 3],
[2, 3, 4],
[3, 4, 5]

Output: [3]

Input : [1, 2, 3],
[4, 5, 6],
[7, 8, 9]

Output: [ ]

There are the following approaches for finding the common elements in all rows of a given matrix using JavaScript which are as follows:

Table of Content

  • Using Set Intersection
  • Sorting and Comparing

Similar Reads

Using Set Intersection

This method involves comparing sets to find common elements among rows in a matrix. It’s a straightforward method that simplifies the process of identifying shared elements efficiently....

Sorting and Comparing

This method involves sorting the rows of the matrix using sort() method and comparing them to identify common elements using compare() method. It’s a straightforward technique that provides an alternative way to uncover shared elements within the matrix using JavaScript....