How to Compare and Get Difference between two Arrays in JavaScript

Published: 09 December 2023
on channel: Tuts Make
54
0

There are a few ways to compare and get the difference between two arrays in JavaScript. Here are a few methods:

Using the indexOf() method:

The indexOf() method returns the index of the first occurrence of a value in an array. We can use this method to compare two arrays by checking if each element in one array exists in the other array. If all elements exist, then the arrays are equal. Otherwise, they are not equal.

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

const areArraysEqual = array1.every((element) = array2.indexOf(element) !== -1);

console.log(areArraysEqual); // true

Using the filter() method:

The filter() method returns a new array containing all elements of the original array that pass a test. We can use this method to compare two arrays by filtering out any elements that are not present in both arrays. The resulting array will contain the elements that are different between the two arrays.

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

const difference = array1.filter((element) = array2.indexOf(element) === -1);

console.log(difference); // [4]

#ReadMore
#https://www.tutsmake.com/comparing-tw...

#javascript #compare #find #get #difference #between #two #array

javascript get difference between two arrays,
javascript compare and get difference between two arrays
How to get the difference between two arrays in JavaScript?
Get the Difference between Two Arrays in JavaScript
find difference between two arrays javascript
JavaScript: Find the difference of two arrays
compare two arrays javascript for unmatched
how to compare two arrays and get the difference javascript
Find difference between two arrays in JavaScript
How to get the difference between two arrays js
how to compare and get difference between two arrays javascript