Javascript arrays are equal

JavaScript array equality: A smarter way to compare two arrays

Since JavaScript array type is actually a special object type, comparing two arrays directly with === or == operator will always return false :

This is because JavaScript object type compares the references for the variables instead of just the values. When you need to check for the equality of two arrays, you’ll need to write some code to work around the equality operators == and === result.

There are two ways you can check for array equality in JavaScript:

This tutorial will show you how to do both. Let’s start with the first method

Checking array equality with every() and includes() method

To check if arrOne is equal to arrTwo , you can use the every() method to loop over the first array and see if each element in the first array is included in the second array.

Читайте также:  Vendor composer autoload classmap php

Take a look at the following example:

But since the code above only checks if elements of the first array is found in the second array, the result will still be true when either array has more elements than the other.

The following example shows how the equality check returns true even when arrOne has more elements than arrTwo :

To handle the length differences, you need to check if the length property of both arrays is equal as shown below:

And that’s how you can check for array equality using a combination of every() and includes() method. Next, you will learn how to do the same check manually with a for loop and the indexOf() method.

Checking array equality with for loop and indexOf() method

Another way to check for array equality is to replace the every() method with the for loop and use the indexOf() method to see if the indexOf() the first array elements are not -1 inside the second array.

First, you need to create the result variable with false as its initial value:

Then, you need to create an if block to check if the array lengths are equal. Only when the length properties are equal will you check on the array values:
 Finally, you need to write the code inside the for loop that will check for the existence of arrOne elements inside arrTwo using the indexOf() method. The syntax will be arrTwo.indexOf(arrOne[i]) !== -1 .

The result of the indexOf() method will return either true or false , and it will be assigned as the new value of result variable. When the result is false , you must stop the iteration because there’s no point in checking the equality further.

And with that, you can check if your arrays are actually equal and having the same elements.

Learn JavaScript for Beginners 🔥

Get the JS Basics Handbook, understand how JavaScript works and be a confident software developer.

A practical and fun way to learn JavaScript and build an application using Node.js.

About

Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.

Type the keyword below and hit enter

Tags

Click to see all tutorials tagged with:

Источник

How to check for array equality using Javascript?

In this article, we cover the different methods to compare two arrays and check if they are equal using javascript. In this process we will also understand the pros and cons of various methods used.

If you are new to the concept of array equality, each section of the article would be useful. However, If you are here to refresh your knowledge, jump straight to the implementation. Go to methods

Table of Contents

Introduction to equality in javascript

Equality is a tricky subject when it comes to javascript. There are technically 4 ways to compare if two values are equal in javascript. Of these, the two most common methods are the == operator, known as abstract equality and the === operator, known as strict equality. Before diving into checking for array equality, let us understand how these equality operators work in javascript.

Strict Equality With ===

Given 2 values x and y, the strict equality checks for equality in the following way:

  1. Check the types of x and y. If they are of different types, return false.
  2. If x and y are numbers, it checks if either of x or y is NaN, and returns false if one is NaN. If both x and y are either +0 or -0, return true. Otherwise, it also checks to see if they are the same number.
  3. If x and y are both null or both undefined, it returns true.
  4. If x and y are both booleans, strings, or symbols, then it compares them by value.
  5. If x and y are both objects, it returns true if and only if they reference the same object.

In Javascript, arrays are considered to be objects, so the === operator only returns true if both the arrays have the same reference

// comparing arrays using strict equality const a = [1, 2, 3]; const b = [1, 2, 3]; a === a; // true a === b; // false (different reference) 

Abstract Equality With ==

Here is a brief overview of how the == operator compares if x and y are equal.

  1. If x and y are of the same type, check if x === y
  2. If x and y are both either null or undefined, return true.
  3. If x is a number and y is a string, convert y to a number and then compare using ===. Similarly, if x is a boolean or string, and y is a number, convert x to a number.
  4. If x or y is a boolean, convert the other value of a number and compare them.
  5. If x is an object and y is a symbol, string, or number, try to convert x to a primitive using valueof() and then compare using ===.

Abstract equality comparison is responsible for many of the strange edge cases that JavaScript is so famous for are covered extensively in this article.

In general, you should always use === rather than == unless you’re confident about what you are doing and have an idea of the expected outcome.

Although there are 4 ways to check if two arrays are equal, none of them consider the deep equality (where you compare even the contents of your objects recursively until all you need to compare are the primitive fields) between the arrays.

Checking for array equality using javascript

Here are 3 ways to check if two arrays are equal.

1) Both arrays have the same length and their values are equal

In this method, we compare if each value of a is equal to the value of b. We have to keep in mind that this will work well if all the values of arrays a and b are primitives and not objects.

// comparing arrays to check for equality - method 1 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); // false arrayEquals(a, c); // true 

2) Deep Equality with POJOs (Plain old java object)

The function arrayEquals() works well for primitive objects as seen above, but falls short if you want to compare arrays containing objects by value. Let’s take a look at the example below:

const a = [< answer: 42 >, < powerLevel: 9001 >]; const b = [< answer: 42 >, < powerLevel: 9001 >]; // false, because < answer: 42 >!== < answer: 42 >, different references arrayEquals(a, b); 

One simple way to go about this with minimal code and no external libraries is to use compare them by their JSON.stringify() output

// method 2 to check if two arrays with objects are equal const a = [< answer: 42 >, < powerLevel: 9001 >]; const b = [< answer: 42 >, < powerLevel: 9001 >]; const c = [< answer: 42 >, < password: 'taco' >]; JSON.stringify(a) === JSON.stringify(b); // true JSON.stringify(a) === JSON.stringify(c); // false 

However, there is one edge case. Since undefined is not a valid JSON value, JSON.stringify() converts undefined to null. So the JSON.stringify() outputs of the arrays shown below will be the same even though they aren’t the same in reality.

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

3) Comparing arrays to check for equality using Lodash’s isequal()

As discussed above, using JSON.stringify() to compare array equality not only causes the undefined vs null quirk but also doesn’t take into account object types. As far as JSON.stringify() is concerned, an object with a toJSON() function that returns 25 is the same as the number 25.

const a = [ < toJSON: () =>25 >]; const b = [25]; JSON.stringify(a); // '[42]' JSON.stringify(b); // '[42]' 
class MyClass < constructor(obj) < Object.assign(this, obj); >> const a = [new MyClass(< answer: 42 >)]; const b = [< answer: 42 >]; JSON.stringify(a) === JSON.stringify(b); // true 

On the other hand, using Lodash’s isequal() function takes all of this into account

Note: Lodash is a JavaScript library that provides utility functions for a common programming task.

//using loadsh to compare array equality const _ = require('lodash'); class MyClass < constructor(obj) < Object.assign(this, obj); >> const a = [new MyClass(< answer: 42 >)]; const b = [< answer: 42 >]; _.isEqual(a, b); // false 

Parting Words:

To conclude, to compare arrays to check for equality, 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.

Источник

Compare Arrays in JavaScript

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; // true a === b; // false

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); // false arrayEquals(a, c); // true

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 >]; // false, because < answer: 42 >!== < answer: 42 >, different references 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); // true JSON.stringify(a) === JSON.stringify(c); // false

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); // '[42]' JSON.stringify(b); // '[42]'

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); // true

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); // false

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

Источник

Оцените статью