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

In JavaScript, comparing arrays directly with == or === compares references, not values. To check if two arrays contain the same values (regardless of order), we need custom comparison logic.

The Problem with Direct Comparison

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

console.log(firstArray === secondArray);  // false
console.log([1, 2] === [1, 2]);          // false - different objects
false
false

Using Sort and Compare Method

The most reliable approach is to sort both arrays and compare each element:

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 

Both are equals

Using JSON.stringify() Method

For simple arrays, you can convert sorted arrays to strings and compare:

function compareArraysWithJSON(arr1, arr2) {
    if (arr1.length !== arr2.length) return false;
    return JSON.stringify(arr1.sort()) === JSON.stringify(arr2.sort());
}

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

console.log(compareArraysWithJSON(firstArray, secondArray));  // true

var thirdArray = [100, 200, 500];
console.log(compareArraysWithJSON(firstArray, thirdArray));   // false
true
false

Comparison of Methods

Method Performance Works with Objects? Handles Nested Arrays?
Sort and Loop Good No No
JSON.stringify() Fair Limited Yes

Key Points

  • Direct array comparison with === compares references, not values
  • Always check array lengths first for performance
  • Use concat() to avoid modifying original arrays when sorting
  • The sort-and-compare method works reliably for primitive values

Conclusion

The sort-and-compare method is the most reliable way to check if arrays contain the same values. Use JSON.stringify() for simple cases, but prefer explicit comparison for better control and performance.

Updated on: 2026-03-15T23:18:59+05:30

394 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements