54

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
Sudharsan S
  • 15,058
  • 3
  • 28
  • 49

10 Answers10

152

You could use Array.prototype.every().(A polyfill is needed for IE < 9 and other old browsers.)

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

var is_same = (array1.length == array2.length) && array1.every(function(element, index) {
    return element === array2[index]; 
});

THE WORKING DEMO.

xdazz
  • 154,648
  • 35
  • 237
  • 264
53

A less robust approach, but it works.

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

console.log(a===b);
user2421180
  • 669
  • 5
  • 7
  • 14
    what if the array elements are not in the same order? this would not work – fenec Oct 21 '15 at 15:47
  • 7
    works perfectly if you know that the array is in the same order (like I do). however you could sort the array elements by `sort()` and this should then solve the op's problem. – luke_mclachlan Feb 26 '16 at 13:28
  • 8
    This approach gives the wrong answer if a = `[2, 4, 5].toString()` and b = `["2,4", 5].toString()`. – Anderson Green Apr 25 '17 at 21:52
  • I believe JSON.jstringify would be better for a universal case. However, it is not as performant from what I understand @AndersonGreen – BigDreamz Apr 05 '20 at 21:49
15
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; 
}
Adam Rackis
  • 81,646
  • 52
  • 262
  • 388
  • 3
    Here's a fiddle to play with (same answer, different way to iterate): http://jsfiddle.net/jimschubert/85M4z/ – Jim Schubert Mar 14 '14 at 03:16
  • A multi-dimensional array version is available here: http://stackoverflow.com/questions/7837456/comparing-two-arrays-in-javascript – Uncle Troy Sep 29 '14 at 00:56
10

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));
}
David G
  • 4,792
  • 1
  • 21
  • 18
  • Unfortunately, this gives false positives. For example: `arraysEqual(23, "")` – Ron Martinez Jul 29 '17 at 03:57
  • This is deliberate. *not an array* == *not an array* – David G Jul 30 '17 at 15:56
  • I think it's debatable whether or not `arraysEqual` should be allowed to receive non-array inputs at all. That said, it's still good to be aware of the aforementioned "gotcha". – Ron Martinez Jul 30 '17 at 22:50
  • My assumption is that it is better to sanitise the inputs than have to wrap every invocation in a `try/catch` block lest it bomb your program. It's a design decision as to what calling it with non-array arguments should do. If you want to throw in this case, then go for it. – David G Aug 07 '17 at 01:27
  • 1
    as for me it's better - const areCollectionsSame = (a: unknown, b: unknown) => Array.isArray(a) && Array.isArray(b) ? a.length === b.length && a.every(el => b.includes(el)) : false; – Lonli-Lokli Nov 22 '21 at 14:15
  • Your second function also gives false positives: `arraysContainSame([1,1,2], [1,2,2])`. This is rarely what you want, you probably want to count multiplicity. – Chrispher May 16 '22 at 09:00
7

You could try this simple approach

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

console.log(array1.join('|'));
console.log(array2.join('|'));

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

array1 = [[1,2],[3,4],[5,6],[7,8]];
array2 = [[1,2],[3,4],[5,6],[7,8]];

console.log(array1.join('|'));
console.log(array2.join('|'));

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

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.');
}
  • The original question stated that the position and value had to be the same. If the position is not important then you can just sort the two arrays first. – Steve Bucknall May 10 '15 at 12:53
  • Converting to string is not reliable, as it fails when the first array is `[4,8,9,10]` and the second is `["4|8",9,10]` for example. – Broxzier Mar 24 '18 at 14:05
  • This was a way easier solution for me I am comparing for exact values between two matrices and don't have bitwise OR operators in my array... @Broxzier – StefanBob Aug 02 '19 at 21:56
4

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)
2

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
qais
  • 1,778
  • 3
  • 19
  • 31
omarjebari
  • 3,937
  • 1
  • 29
  • 26
1

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);
Zia
  • 111
  • 1
  • 6
  • Thanks! I'm using this! I appreciate how concise this is – wle8300 Jun 25 '17 at 08:22
  • The above code is more usable in many cases. I am using myself. – Zia Aug 23 '17 at 11:26
  • This won't work for these two arrays: a = [1, 2, 3, 4, 2] and b = [1, 2, 3, 4, 3]. Your function will return true. The sort() + toString() method seems the most reliable so far. – Florian G Nov 19 '21 at 19:36
0
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

Arun Vinoth - MVP
  • 21,521
  • 14
  • 57
  • 157
-1

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;
}
UVM
  • 9,725
  • 5
  • 40
  • 64
  • 3
    A rule of thumb here is not to mess with objects you don't own. `Array.prototype` is a built-in prototype object for type Arrays and this will cause inconsistency while working in a team. – Farzad Yousefzadeh Nov 13 '16 at 10:49