Como comparar arrays em js

To compare two Arrays in JavaScript, you should check that the length of both arrays should be the same, the objects presented in it be the same type, and each item in one array is equivalent to the counterpart in the compared array.

This tutorial will show you some ways of comparing two arrays.

One of the methods is converting both strings to JSON string and compare the strings to each other to determine equality. The JSON.stringify() method is used to convert the array to a string:

Como comparar arrays em js
Javascript JSON.stringify method

let firstArr = [1, 2, [3, 4, 5]]; let secondArr = [1, 2, [3, 4, 5]]; let isEqual = JSON.stringify(firstArr) === JSON.stringify(secondArr); console.log(isEqual);

If the array contains null and undefined, the given solution won’t work.

You can also invoke toString() for camparing an array of numbers and string:

Como comparar arrays em js
Javascript toString method

let firstArr = [1, 2, 3, 4, 5]; let secondArr = [1, 2, 3, 4, 5]; let isEqual = firstArr.toString() === secondArr.toString(); console.log(isEqual);

An alternate way of the above solution is Array.prototype.every() to compare each element of the array with the elements of another array:

Como comparar arrays em js
Javascript compare two arrays elements

let firstArr = [1, 2, 3, 4, 5]; let secondArr = [1, 2, 3, 4, 5]; let isEqual = firstArr.length === secondArr.length && firstArr.every((value, index) => value === secondArr[index]); console.log(isEqual);

Arrays are list-like objects, and their elements are properties with names 0, 1, 2 .. etc. They have special properties: length and many functions that manipulate the elements. Neither the length nor the types of the elements are fixed.

The arrays are zero-indexed, meaning that the first element is at index 0, and the index of the last element is equivalent to the value of the length property minus 1.

// program to compare two arrays function compareArrays(arr1, arr2) { // compare arrays const result = JSON.stringify(arr1) == JSON.stringify(arr2) // if result is true if(result) { console.log('The arrays have the same elements.'); } else { console.log('The arrays have different elements.'); } } const array1 = [1, 3, 5, 8]; const array2 = [1, 3, 5, 8]; compareArrays(array1, array2);

Output

The arrays have the same elements.

The JSON.stringify() method converts an array into JSON string.

JSON.stringify([1, 3, 5, 8]); // "[1,3,5,8]"

Then, the two array strings are compared using ==.

Example 2: Compare Arrays using for Loop

// program to extract value as an array from an array of objects function compareArrays(arr1, arr2) { // check the length if(arr1.length != arr2.length) { return false; } else { let result = false; // comparing each element of array for(let i=0; i<arr1.length; i++) { if(arr1[i] != arr2[i]) { return false; } else { result = true; } } return result; } } const array1 = [1, 3, 5, 8]; const array2 = [1, 3, 5, 8]; const result = compareArrays(array1, array2); // if result is true if(result) { console.log('The arrays have the same elements.'); } else { console.log('The arrays have different elements.'); }

Output

The arrays have the same elements.

In the above program,

The length of the array elements are compared using the length property. If both arrays have different lengths, false is returned.

Else,

  • The for loop is used to iterate through all the elements of the first array.
  • During each iteration, elements of the first array are compared to corresponding elements of the second array. arr1[i] != arr2[i]
  • If the corresponding array elements of both arrays are not equal, false is returned and the loop terminates.
  • If all elements are equal, true is returned.

Note: The above program does not work if the array element contains objects.

For example,

array1 = [1, {a : 2}, 3, 5];

Mar 20, 2020

Arrays are objects in JavaScript, so the triple equals operator === only returns true if the arrays are the same reference.

const a = [1, 2, 3]; const b = [1, 2, 3]; a === a; a === b;

How do you compare whether two arrays are equal? Equality is a tricky subject: the JavaScript spec defines 4 different ways of checking if two values are "equal", and that doesn't take into account deep equality between objects.

In cases like this, it helps to be as explicit as possible about what you mean by "equal." In software engineering, asking a question in the right way often makes the answer obvious.

With that in mind, here's 3 definitions of equality for arrays and how to check them.

Same Length, Each Value Equal

One approach for comparing a and b is checking if each value of a is strictly equal to the corresponding value of b. This works well if all the elements of the arrays are primitives as opposed to objects.

const a = [1, 2, 3]; const b = [4, 5, 6]; const c = [1, 2, 3]; function arrayEquals(a, b) { return Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((val, index) => val === b[index]); } arrayEquals(a, b); arrayEquals(a, c);

Deep Equality With POJOs

The previous arrayEquals() function works great for primitive values, but falls short if you want to compare objects by value.

const a = [{ answer: 42 }, { powerLevel: 9001 }]; const b = [{ answer: 42 }, { powerLevel: 9001 }]; arrayEquals(a, b);

One neat way to take into account object values is comparing arrays by their JSON.stringify() output.

const a = [{ answer: 42 }, { powerLevel: 9001 }]; const b = [{ answer: 42 }, { powerLevel: 9001 }]; const c = [{ answer: 42 }, { password: 'taco' }]; JSON.stringify(a) === JSON.stringify(b); JSON.stringify(a) === JSON.stringify(c);

This approach is handy because it requires minimal code and no outside libraries. However, comparing JSON.stringify() output has an unfortunate edge case that may be a problem depending on your use case. Since undefined isn't a valid JSON value, the below arrays have the same JSON.stringify() output, because JSON.stringify() converts undefined to null.

const a = [undefined]; const b = [null];

Using Lodash's isEqual()

In addition to the null vs undefined quirk, comparing JSON.stringify() output also doesn't take into account object types. As far as JSON.stringify() is concerned, an object with a toJSON() function that returns 42 is the same as the number 42.

const a = [{ toJSON: () => 42 }]; const b = [42]; JSON.stringify(a); JSON.stringify(b);

Similarly, a custom object is the same as a POJO:

class MyClass { constructor(obj) { Object.assign(this, obj); } } const a = [new MyClass({ answer: 42 })]; const b = [{ answer: 42 }]; JSON.stringify(a) === JSON.stringify(b);

Lodash's isEqual() function, on the other hand, takes all this into account.

const _ = require('lodash'); class MyClass { constructor(obj) { Object.assign(this, obj); } } const a = [new MyClass({ answer: 42 })]; const b = [{ answer: 42 }]; _.isEqual(a, b);

Lodash's isEqual() function is the way to go if you need all the bells and whistles of checking that objects have the same class. The JSON.stringify() approach works well for POJOs, just make sure you take into account null and only use it with trusted data - toJSON() can be a security vulnerability.

More Fundamentals Tutorials