Сопоставление двух массивов javascript

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.

Читайте также:  Html if else python

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

Прямое сравнение массивов всегда будет давать результат false . Поскольку массив, как объект, указывает на ссылку памяти, где хранится «значение». И эти ссылки всегда будут разными, за исключением случая когда мы сравниваем один и тот же объект (массив).

[1, 2, 3] === [1, 2, 3]; // false [1, 2, 3] > [1, 2, 3]; // false [1, 2, 3]  [1, 2, 3]; // false 
const a = [10, 11]; const b = a; console.log(a === b); // true 

В последнем случае мы сравниваем один и тот же массив и получаем true , т.к. в b скопировалась ссылку на этот массив, а не значение.

Источник

How to Compare Arrays in JavaScript

How to Compare Arrays in JavaScript

Arrays in JavaScript are everywhere because of how useful it is to store several pieces of data within a single variable.

However, sometimes it is necessary to compare arrays directly to see if they contain the same values.

In this post, we’ll learn the best ways to compare different arrays in JavaScript.

How to compare arrays in JavaScript

Before we look functioning ways to compare arrays in JavaScript, let’s first look at an example that doesn’t work.

First let’s define two arrays:

You might assume that the following code would work:

However, this returns false because the === operator compares the reference of the arrays, not the values.

This would work in this example:

However, this isn't very likely in a real-world scenario.

Let’s look into some valid ways to compare arrays.

How to compare arrays with JSON.stringify()

The first way to compare arrays is to use the JSON.stringify() method.

This involves turning both arrays into strings and then comparing the strings.

This works in simple arrays, however if the order between the elements are different, it will result in different JSON, and therefore return false .

Another way you can compare arrays is by using the every() method.

This method returns true only if every element in the array passes the test.

The test we can pass is a function that compares the elements of the array with the elements of the other array.

We can also do a length check to ensure that the arrays are the same length, because if they’re not, we know they’re not equal.

 element === array2[index]); const equal = sameLength && sameValues; console.log(equal); 
This works for more complex arrays, however, the order here still matters.

If the order is different, it will return false .

 element === array2[index]); const equal = sameLength && sameValues; console.log(equal); 

How to compare arrays with the every() and includes() methods

We can use the every() and includes() methods to compare arrays.

This ensures that order doesn’t matter, and that the arrays contain the same values.

Rather than doing a direct comparison like before, we instead check if the element exists in the other array, regardless of the order.

 array2.includes(element)); const equal = sameLength && sameValues; console.log(equal); 
In this post, we learned how to compare arrays in JavaScript.

Your options include using JSON.stringify() to compare the JSON strings, or using every() and includes() to directly compare the individual values of the arrays.

Thanks for reading and happy coding!

If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on Twitter! You can also join the conversation over at our official Discord!

Give feedback on this page , tweet at us, or join our Discord !

Источник

Как сравнить два массива в js?

Есть допустим 2 массива.
Одинаковые по содержимому, только в одном на один элемент больше.
Как их сравнить, что бы вытащить элемент которого не хватает во втором массиве?
Заранее спасибо.

function diff(a1, a2) < return a1.filter(i=>a2.indexOf(i)<0) .concat(a2.filter(i=>a1.indexOf(i) <0)) >function compare(a1, a2) < return a1.length == a2.length && a1.every((v,i)=>v === a2[i]) >

upd: в ES7 (2016) появился метод includes

const diff = function(a1, a2) < return a1.filter(i=>!a2.includes(i)) .concat(a2.filter(i=>!a1.includes(i))) >

Ckomop0x

vetero4eg

Понимаю, что уже не актуально, но, это решение не поможет вернуть разницу, если элементы повторяются (по значению), ну например

IonDen

var a = [1, 2, 3, 4, 5], b = [1, 2, 3, 4, 5, 6]; function diff (a, b) < if (a.length >b.length) < return _.difference(a, b); >else < return _.difference(b, a); >> console.log(_.difference(b, a)); // [6]

geek01

Я и не знал про такие возможнсти js)) Только вы забыли вывести саму функцию diff(b, a), вместо этого выводите сразу обработчик разницы без сравнения, какой массив больше

geek01

Я только начинаю учить. Для меня более понятный такой формат кода. Может кому то поможет. Добавил сортировку от меньшего к большему и наоборот.

var a1 = [1,2,3,99,88,77,89,-99,-199] a2 = [1,2,3,8,89,9,-99,6,-77] function sortMyArray(a,b) < return b - a; >function sortMyArrayR(a,b) < return a - b; >function comparison () < return a1.filter(i=>a2.indexOf(i)<0).concat(a2.filter(i=>a1.indexOf(i) <0)) >write.innerHTML += "["+comparison(a1,a2).sort(sortMyArray)+"]"; arr.innerHTML += "["+ a1.sort(sortMyArray).toString()+"] \t["+a2.toString()+"]" writeRev.innerHTML += "["+comparison(a1,a2).sort(sortMyArrayR)+"]";

Источник

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