Javascript array element compare

JavaScript Program to Compare Elements of Two Arrays

To understand this example, you should have the knowledge of the following JavaScript programming topics:

Example 1 : Compare Arrays Using JSON.stringify()

// 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);
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; ielse < 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
The arrays have the same elements.

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

  • 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.

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

Источник

Comparing Arrays in JavaScript – How to Compare 2 Arrays in JS

Joel Olawanle

Joel Olawanle

Comparing Arrays in JavaScript – How to Compare 2 Arrays in JS

When handling logic with JavaScript, you might need to compare two arrays to see if they are equal or not.

Really, this shouldn’t be difficult, as you’d think we could easily use either the loose equality (double equals — == ) or the strict equality (triple equals — === ). But unfortunately, you cannot use them in this case.

let array1 = [11, 22, 33]; let array2 = [11, 22, 33]; console.log(array1 == array2); //false console.log(array1 === array2); //false 

This happens because JavaScript arrays have a type of Object:

let arrayType = typeof(array1); console.log(arrayType); //"Object" 

Objects are not compared based on their values but based on the references of the variables:

console.log(array1[0] == array1[0]); //true console.log(array1[1] === array1[1]); //true 

But this is not what you want. Instead, you want to be able to compare both arrays directly and return just one boolean value without having to check each element one by one.

In this article, you will learn the various ways you can compare two arrays in JavaScript to see if they are similar or not.

How to Compare Two Arrays by Converting to Strings

A common and quite straightforward approach you can use to compare two arrays is first to convert these arrays to string form.

There are two different methods that you can use: you can decide to convert your array to JSON text using the JSON.stringify() method, or you can use the .toString() method to return your array as a string.

Note: Both methods are different, as you can see below:

let array = [11, 22, 33]; console.log(JSON.stringify(array)); //"[11,22,33]" console.log(array.toString()); //"11,22,33" 

Method 1: How to use JSON.stringify()

This method allows you to serialize each array by converting the array to a JSON string. You can then compare the two JSON strings.

let array1 = [11, 22, 33]; let array2 = [11, 22, 33]; console.log(JSON.stringify(array1) === JSON.stringify(array2)); //true 

We can also decide to create a reusable function that helps us compare any two arrays we pass into it:

const compareArrays = (a, b) => < return JSON.stringify(a) === JSON.stringify(b); >; let array1 = [11, 22, 33]; let array2 = [21, 22, 23]; let array3 = [11, 22, 33]; console.log(compareArrays(array1, array2)); //false console.log(compareArrays(array1, array3)); //true 

Method 2: How to use .toString()

Similar to JSON.stringify() , this method converts any data type to a string and can similarly convert an object to a string.

let array1 = [11, 22, 33]; let array2 = [11, 22, 33]; console.log(array1.toString() === array2.toString()); //true 

You can also decide to create a reusable function that helps you compare any two arrays you pass into it:

const compareArrays = (a, b) => < return a.toString() === b.toString(); >; let array1 = [11, 22, 33]; let array2 = [21, 22, 23]; let array3 = [11, 22, 33]; console.log(compareArrays(array1, array2)); //false console.log(compareArrays(array1, array3)); //true 

Note: You should use the JSON.stringify() method, as it only serializes your JavaScript array. The array still takes the shape of an array, but it’s only parsed to become the string version of the array.

How to Compare Two Arrays by Lopping Through Their Values

The methods above fall short in some scenarios. For example, when one array has a value of null and another has a value of undefined , when we use the strict comparison, we get false by default – which is correct:

console.log(null === undefined); //false 

But when we use the JSON.Strigify() or .toString() methods you get true , which shouldn’t be the case:

let array1 = [11, null, 33]; let array2 = [11, undefined, 33]; console.log(JSON.stringify(array1) === JSON.stringify(array2)); //true console.log(array1.toString() === array2.toString()); //true 

A better approach would be to compare the array’s length and then loop through and compare each element of the array.

Method 1: using every()

The every() method helps you execute a function for each element of your array. This function is referred to as the call back function. It has access to some basic parameters like the element, index, and lots more, which we can use within the function:

// Syntax array.every((currentValue, index, arr)=> < . >) 

In this method, we’ll first test if the lengths of the two arrays are comparable. Then we’ll loop through one array and using its index to compare its elements to those in the second array:

const compareArrays = (a, b) => a.length === b.length && a.every((element, index) => element === b[index]); let array1 = [11, 22, 33]; let array2 = [21, 22, 23]; let array3 = [11, 22, 33]; console.log(compareArrays(array1, array2)); //false console.log(compareArrays(array1, array3)); //true 

And when we have null and undefined as part of our Array elements, it will be able to detect that they are not the same:

const compareArrays = (a, b) => a.length === b.length && a.every((element, index) => element === b[index]); let array1 = [11, null, 33]; let array2 = [21, 22, 23]; let array3 = [11, undefined, 33]; console.log(compareArrays(array1, array2)); //false console.log(compareArrays(array1, array3)); //false 

Method 2: using a for loop

The every() method has a better syntax. Still, another way we can implement the method is to use other iteration methods like the for loop, forEach() or map() alongside if statements. These can be easier for a newbie to grasp.

const compareArrays = (a, b) => < if (a.length !== b.length) return false; else < // Comparing each element of your array for (var i = 0; i < a.length; i++) < if (a[i] !== b[i]) < return false; >> return true; > >; let array1 = [21, null, 33]; let array2 = [21, 22, 23]; let array3 = [21, undefined, 33]; let array4 = [21, 22, 23]; console.log(compareArrays(array1, array2)); //false console.log(compareArrays(array1, array3)); //false console.log(compareArrays(array2, array4)); //true 

In both methods above, you will first check for the length, because if the length is not equal, it automatically means both arrays are not equal and then returns false .

If the length is equal, then we begin to check each element. It returns false as soon as two elements on the same index in both arrays are different.

Wrapping Up

This article taught you how to compare two arrays in JavaScript using two major approaches.

These approaches are to convert the array to a string before comparing them, or you can loop through to check if their values are similar to each other for a more detailed comparison.

Note: The double equals checks if both values are equal, while the triple equals checks if both values and their data types are equal. You can read more about both types of equality here.

Embark on a journey of learning! Browse 200+ expert articles on web development. Check out my blog for more captivating content from me.

Источник

JavaScript: The best way to compare array elements

JavaScript arrays are a special type of objects, and just like regular objects, comparison of two arrays will return false even when they contain the same elements:

The equality operator will compare the reference for arrays and objects, so the only way to return true from equality operator is to copy the array object as follows:

But this won’t help much when you need to compare two arrays from different references, so let’s see how you can compare the elements of an array

Compare arrays using JSON

The most common solution is to compare the arrays using JSON.stringify() method so you have two serialized strings.

But this method compares the arrays indirectly, and having the same values in different orders will return false instead of true . If you want to actually compare the elements of two arrays programmatically, you need to use other methods.

Compare arrays with every() method

You can use the combination of comparing the arrays length values and their elements using every() method as follows:

This way, you compare if the element at a specific index is really equal or not. Still, this method requires both arrays to have the same element at the index in order to return true . If you don’t care about the order and only want both arrays to have the same elements, you can use the following method.

Compare out of order array elements

In order to compare array elements that are out of order, you can use the combination of every() and includes() method.

The includes() method determines whether an array includes a certain element among its entries, regardless of the index:

The includes() method are added into JavaScript on ES7, so if you need to support older JavaScript versions, you can use indexOf() method as an alternative.

Since indexOf() returns -1 when the specified element is not found, you can make every() return true when indexOf(element) !== -1 .

Comparing arrays in JavaScript is not straightforward as comparing strings, but if what you need is to compare whether the elements are included, the above methods should suffice for your project.

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:

Источник

Читайте также:  Parse csv with python
Оцените статью