[javascript] How to Compare two Arrays are Equal using Javascript?

I want position of the array is to be also same and value also same.

var array1 = [4,8,9,10];
var array2 = [4,8,9,10];

I tried like this

var array3 = array1 === array2   // returns false

This question is related to javascript jquery arrays

The answer is


You could try this simple approach

_x000D_
_x000D_
var array1 = [4,8,9,10];_x000D_
var array2 = [4,8,9,10];_x000D_
_x000D_
console.log(array1.join('|'));_x000D_
console.log(array2.join('|'));_x000D_
_x000D_
if (array1.join('|') === array2.join('|')) {_x000D_
 console.log('The arrays are equal.');_x000D_
} else {_x000D_
 console.log('The arrays are NOT equal.');_x000D_
}_x000D_
_x000D_
array1 = [[1,2],[3,4],[5,6],[7,8]];_x000D_
array2 = [[1,2],[3,4],[5,6],[7,8]];_x000D_
_x000D_
console.log(array1.join('|'));_x000D_
console.log(array2.join('|'));_x000D_
_x000D_
if (array1.join('|') === array2.join('|')) {_x000D_
 console.log('The arrays are equal.');_x000D_
} else {_x000D_
 console.log('The arrays are NOT equal.');_x000D_
}
_x000D_
_x000D_
_x000D_

If the position of the values are not important you could sort the arrays first.

if (array1.sort().join('|') === array2.sort().join('|')) {
    console.log('The arrays are equal.');
} else {
    console.log('The arrays are NOT equal.');
}

If you comparing 2 arrays but values not in same index, then try this

var array1=[1,2,3,4]
var array2=[1,4,3,2]
var is_equal = array1.length==array2.length && array1.every(function(v,i) { return ($.inArray(v,array2) != -1)})
console.log(is_equal)

Here goes the code. Which is able to compare arrays by any position.

var array1 = [4,8,10,9];

var array2 = [10,8,9,4];

var is_same = array1.length == array2.length && array1.every(function(element, index) {
    //return element === array2[index];
  if(array2.indexOf(element)>-1){
    return element = array2[array2.indexOf(element)];
  }
});
console.log(is_same);

Use lodash. In ES6 syntax:

import isEqual from 'lodash/isEqual';
let equal = isEqual([1,2], [1,2]);  // true

Or previous js versions:

var isEqual = require('lodash/isEqual');
var equal = isEqual([1,2], [1,2]);  // true

A less robust approach, but it works.

a = [2, 4, 5].toString();
b = [2, 4, 5].toString();

console.log(a===b);

function isEqual(a) {
if (arrayData.length > 0) {
    for (var i in arrayData) {
        if (JSON.stringify(arrayData[i]) === JSON.stringify(a)) {
            alert("Ya existe un registro con esta informacion");
            return false;
        }
    }
}
}

Check this example


A more modern version:

function arraysEqual(a, b) {
  a = Array.isArray(a) ? a : [];
  b = Array.isArray(b) ? b : [];
  return a.length === b.length && a.every((el, ix) => el === b[ix]);
}

Coercing non-array arguments to empty arrays stops a.every() from exploding.

If you just want to see if the arrays have the same set of elements then you can use Array.includes():

function arraysContainSame(a, b) {
  a = Array.isArray(a) ? a : [];
  b = Array.isArray(b) ? b : [];
  return a.length === b.length && a.every(el => b.includes(el));
}

Try doing like this: array1.compare(array2)=true

Array.prototype.compare = function (array) {
    // if the other array is a falsy value, return
    if (!array)
        return false;

    // compare lengths - can save a lot of time
    if (this.length != array.length)
        return false;

    for (var i = 0, l=this.length; i < l; i++) {
        // Check if we have nested arrays
        if (this[i] instanceof Array && array[i] instanceof Array) {
            // recurse into the nested arrays
            if (!this[i].compare(array[i]))
                return false;
        }
        else if (this[i] != array[i]) {
            // Warning - two different object instances will never be equal: {x:20} != {x:20}
            return false;
        }
    }
    return true;
}

var array3 = array1 === array2

That will compare whether array1 and array2 are the same array object in memory, which is not what you want.

In order to do what you want, you'll need to check whether the two arrays have the same length, and that each member in each index is identical.

Assuming your array is filled with primitives—numbers and or strings—something like this should do

function arraysAreIdentical(arr1, arr2){
    if (arr1.length !== arr2.length) return false;
    for (var i = 0, len = arr1.length; i < len; i++){
        if (arr1[i] !== arr2[i]){
            return false;
        }
    }
    return true; 
}

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?