Syntax error How to know if two arrays have the same values in JavaScript?

How to know if two arrays have the same values in JavaScript?



Let’s say the following are our arrays −

var firstArray=[100,200,400];
var secondArray=[400,100,200];

You can sort both the arrays using the sort() method and use for loop to compare each value as in the below code −

Example

var firstArray=[100,200,400];
var secondArray=[400,100,200];
function areBothArraysEqual(firstArray, secondArray) {
   if (!Array.isArray(firstArray) || ! Array.isArray(secondArray) ||
   firstArray.length !== secondArray.length)
   return false;
   var tempFirstArray = firstArray.concat().sort();
   var tempSecondArray = secondArray.concat().sort();
   for (var i = 0; i < tempFirstArray.length; i++) {
      if (tempFirstArray[i] !== tempSecondArray[i])
         return false;
   }
   return true;
}
if(areBothArraysEqual(firstArray,secondArray))
console.log("Both are equals");
else
console.log("Both are not equals");

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo156.js.

Output

PS C:\Users\Amit\JavaScript-code> node demo156.js
Both are equals
Updated on: 2020-09-12T07:30:28+05:30

351 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements