Open In App

How to get symmetric difference between two arrays in JavaScript ?

Last Updated : 27 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will see how to get the symmetric difference between two arrays using JavaScript.

In Mathematics the symmetric difference between two sets A and B is represented as A Δ B = (A – B) ∪ (B – A)

  • It is defined as a set of all elements that are present in either set A or set B but not in both.
  • In simple words, common elements are discarded from both sets.

For example:

A = { 1, 2, 3, 4, 5, 6}
B = { 4, 5, 6, 7 }
A - B = { 1, 2, 3, 4, 5, 6} - { 4, 5, 6, 7 }
= { 1, 2, 3 }
B - A = { 4, 5, 6, 7 } - { 1, 2, 3, 4, 5, 6}
= { 7, 1, 2, 3 }

A Δ B = ( A - B ) ∪ ( B - A )
= { 1, 2, 3 } ∪ { 7, 1, 2, 3 }
A Δ B = { 1, 2, 3, 7 }

We can achieve this with the following approaches:

Approaches to get Symmetric difference:

Approach 1: Naive method – using Javascript for loop.

Example: In this example, we will be finding the symmetric difference of the two arrays using Javascript for loop.

Javascript
// Defining two arrays and a resultant array
const a = [1, 2, 3, 4, 5, 7, 9];
const b = [5, 6, 7, 8, 9];
const result = [];

// Defining the function with two
// arguments array inputs
function difference(arr1, arr2) {
    let i = 0,
        j = 0;
    let flag = false;

    /* For array 1 */
    for (i = 0; i < arr1.length; i++) {
        // Resetting the flag and the
        // other array iterator
        j = 0;
        flag = false;
        while (j != arr2.length) {
            if (arr1[i] == arr2[j]) {
                flag = true;
                break;
            }
            j++;
        }

        /* If value is not present in the 
            second array then push that value 
            to the resultant array */
        if (!flag) {
            result.push(arr1[i]);
        }
    }
    flag = false;

    // For array 2
    for (i = 0; i < arr2.length; i++) {
        // Resetting the flag and the
        // other array iterator
        j = 0;
        flag = false;
        while (j != arr1.length) {
            if (arr2[i] == arr1[j]) {
                flag = true;
                break;
            }
            j++;
        }

        /* If value is not present in the
            first array then push that value 
            to the resultant array */
        if (!flag) {
            result.push(arr2[i]);
        }
    }
    return result;
}
console.log(difference(a, b));

Output
[ 1, 2, 3, 4, 6, 8 ]

Approach 2: Using the filter() and includes() methods

In this approach, we use the filter() method on the first array and check if each item is not present in the second array using the includes() method. The resulting array contains the elements that are present in the first array but not in the second array.

Syntax:

array1.filter((element) => !array2.includes(element));

Example: In this example, we use  filter() and includes() methods to get the difference between the arrays as shown:

Javascript
// Defining two arrays and a resultant array
const array1 = [1, 2, 3, 4, 5, 7, 9];
const array2 = [5, 6, 7, 8, 9];

// Getting elements in array1 but not array2
const difference1 = array1.filter(
  (element) => !array2.includes(element));

// Getting elements in array2 but not array1
const difference2 = array2.filter(
  (element) => !array1.includes(element));

// Combining the differences
const result = [...difference1, ...difference2];

// Showing the output
console.log(result);

Output
[ 1, 2, 3, 4, 6, 8 ]

Approach 3: Using Set and filter() Method

In this approach, the arrays are converted to Sets using the Set constructor. The Set data structure only allows unique values. By filtering out the elements from the first set that also exist in the second Set, we can obtain the difference.

Syntax:

const difference = [...set1].filter((element) => !set2.has(element));

Example: In this example, we will get the differences of arrays using  set and filter() method and show the combined result as output:

Javascript
// Defining two arrays
const array1 = [1, 2, 3, 4, 5, 7, 9];
const array2 = [5, 6, 7, 8, 9];

// Converting arrrays to sets using set method
const set1 = new Set(array1);
const set2 = new Set(array2);

// Geting the differences using filter method
const difference1 = [...set1].filter((element) => !set2.has(element));
const difference2 = [...set2].filter((element) => !set1.has(element));

// Combining differnce arrays
const result = [...difference1, ...difference2];

// Showing the result as output
console.log(result);

Output
[ 1, 2, 3, 4, 6, 8 ]

Approach 4:Using reduce() and includes() Methods

This method iterates over the first array and checks if each element is present in the second array using the includes() method. It accumulates the elements that are not found in the second array, resulting in the difference between the two arrays.

Syntax:

const difference = array1.reduce((result, element) => {
if (array2.indexOf(element) === -1) {
result.push(element);
}
return result;
}, []);

Example: In this example, we will get the differences of arrays using reduce() and includes() methods and show the combined result as output:

Javascript
// Defining two arrays
const array1 = [1, 2, 3, 4, 5, 7, 9];
const array2 = [5, 6, 7, 8, 9];

// Getting elemment in array1 but not in array2
const difference1 = array1.reduce((result, element) => {
    if (array2.indexOf(element) === -1) {
        result.push(element);
    }
    return result;
}, []);

// Getting elemements in array2 but not in array1
const difference2 = array2.reduce((result, element) => {
    if (array1.indexOf(element) === -1) {
        result.push(element);
    }
    return result;
}, []);

// Combining the diffeerence using spread operator
const result = [...difference1, ...difference2];

// Show the result as output
console.log(result);

Output
[ 1, 2, 3, 4, 6, 8 ]

Using Lodash Library

Using the Lodash library, the xor function computes the symmetric difference between two arrays, returning an array of elements that are unique to each input array. This approach simplifies the process by leveraging Lodash’s built-in utility functions.

Example: In this example we are using lodash library’s xor function to compute the symmetric difference between array1 and array2, returning elements present in one array but not both. The result is logged to the console.

JavaScript
const _ = require('lodash');

const array1 = [1, 2, 3];
const array2 = [3, 4, 5];

const symmetricDifference = _.xor(array1, array2);

console.log(symmetricDifference);

Output:

[1, 2, 4, 5]


Similar Reads

How to Get the Difference Between Two Arrays in JavaScript ?
The problem is to find the difference between two arrays in JavaScript. The objective is to identify the elements that exist in one array but not in the other and return them as a new array. These are the approaches to achieve differences between two arrays are: Table of Content Using the filter() and includes() methodsUsing for Loop and indexOf()
4 min read
How to get the Difference Between Two Arrays in PHP?
Given two Arrays, the task is to get the difference between two arrays in PHP. To get the difference between two arrays, compare both arrays and retrieve values that are present in the first array but not in the second array. Below are the approaches to get the difference between two arrays in PHP: Table of Content Using array_diff() FunctionUsing
3 min read
Javascript Program to check if a matrix is symmetric
A square matrix is said to be symmetric matrix if the transpose of the matrix is same as the given matrix. Symmetric matrix can be obtain by changing row to column and column to row. Examples:  Input : 1 2 3 2 1 4 3 4 3 Output : Yes Input : 3 5 8 3 4 7 8 5 3 Output : No A Simple solution is to do following.  1) Create transpose of given matrix. 2)
2 min read
Get the Difference between Two Sets using JavaScript
Given two Sets and the task is to compute the set difference between the two Sets using JavaScript. This means that the array we subtract should contain all the unique element which is not present in the second array. We can get the difference between two sets using Javascript by the following methods: Use the filter() methodUsing Set delete() Meth
2 min read
HTML5 MathML symmetric Attribute
If the stretchy attribute is set to true, it specifies if the operator should be vertically symmetric around the imaginary Math axis. This attribute is accepted by the &lt;mo&gt; tag only. Syntax: &lt;element symmetric="true|false"&gt; Attribute values: true: It specifies the operator should be vertically symmetric around the imaginary math axis. f
1 min read
Php Program to check if a matrix is symmetric
A square matrix is said to be symmetric matrix if the transpose of the matrix is same as the given matrix. Symmetric matrix can be obtain by changing row to column and column to row. Examples:  Input : 1 2 3 2 1 4 3 4 3 Output : Yes Input : 3 5 8 3 4 7 8 5 3 Output : No A Simple solution is to do following.  1) Create transpose of given matrix. 2)
2 min read
JavaScript Program to Find the Distance Value between Two Arrays
We will be given two integer arrays and an integer d. The task is to calculate the distance between the two given arrays based on the given integer value. The distance value will be calculated as the number of elements arr1[i] such that there is not any element arr2[j] where |arr1[i]-arr2[j]| &lt;= d. Example:Input: arr1 = [4, 5, 8], arr2 = [10, 9,
3 min read
How to Create Nested Arrays from a Nest of Arrays in JavaScript ?
Creating nested arrays from a nest of arrays in JavaScript involves organizing multiple arrays into a hierarchical structure, which is often useful for managing and representing complex data relationships. This process entails encapsulating arrays within other arrays to form multi-dimensional structures. Such nested arrays can represent various dat
3 min read
How to get Difference between two Dates in days using jQuery ?
In this article, we will learn how to find the difference between the 2 dates in days using jQuery. Here, we will take the input for the dates using a jquery datepicker. Considering the given below 2 input Dates, we need to calculate the difference between them which will be returned in a number of days. Input : 02/17/2022 02/10/2022 Output: 7For t
2 min read
Get the relative timestamp difference between dates in JavaScript
Given the 2 JavaScript dates and the job is to get the relative time difference between them(eg.. 2 hours ago, 2.5 days ago, etc.) Here 2 approaches are discussed with the help of javaScript. Approach 1: Get the prevDate and currDate in a variable using Date() object .Calculate the milliseconds in Minute, Hour, Day, Month and in an Year.Calculate t
4 min read