Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
July 19, 2022 08:58 am GMT

Find symmetric difference between two arrays in JavaScript

The goal of this post is to find a symmetric difference between two arrays in JavaScript which can be very helpful for total beginners.

We will compare two arrays and return a new one with items that are found only in one of the arrays. In other words, we will remove the ones that exist in both arrays.

We will use two arrays:

const arrayOne = [1, 2, 3, 5];const arrayTwo = [1, 2, 3, 4, 5];

Using Array.prototype.filter()

The filter() method is a function that creates a new array and returns a value that will pass the specific condition.

The plan will be like this:
a. First, we will compare arrayOne to ArrayTwo using another method includes().
b. Secondly, we will compare ArrayTwo to ArrayOne using includes() once again.
c. Then, we will use a third method Array.prototype.concat() to merge the result of the first two steps.

Let's get started!

const arrayOne = [1, 2, 3, 5];const arrayTwo = [1, 2, 3, 4, 5];const stepOne = arrayOne.filter(item => !arrayTwo.includes(item));const stepTwo = arrayTwo.filter(item => !arrayOne.includes(item));const symmetricDifference = stepOne.concat(stepTwo);

Let's analyze what happened here:

  1. First we took the arrayOne and used a filter() method which returns an array that passes the next condition: check each item in arrayOne and return only those which aren't included in arrayTwo.
  2. Next, we took the arrayTwo and used a filter() method which returns an array that passes the next condition: check each item in arrayTwo and return only those which aren't included in arrayOne.
  3. Finally, we took the results of the first and second steps, the array of items of arrayOne which do not exist in arrayTwo and the array of items of arrayTwo which do not exist in arrayOne, and used concat() method to merge those two.

There are many other ways to do this however if you are a beginner this is all you need to find symmetric difference between two arrays in JavaScript.


Original Link: https://dev.to/catherineisonline/find-symmetric-difference-between-two-arrays-in-javascript-7k4

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To