Semanticize intermediate headings
This commit is contained in:
@ -7,7 +7,7 @@ cover: blog_images/coconuts.jpg
|
||||
excerpt: Learn how you can compare two arrays in JavaScript using various different techniques.
|
||||
---
|
||||
|
||||
**Equality comparison**
|
||||
### Equality comparison
|
||||
|
||||
Comparing two arrays in JavaScript using either the loose or strict equality operators (`==` or `===`) will most often result in `false`, even if the two arrays contain the same elements in the same order. This is due to the fact that arrays and objects are compared by reference and not by value in JavaScript, which means this solution does not produce the desired result:
|
||||
|
||||
@ -18,7 +18,7 @@ const b = [1, 2, 3];
|
||||
a === b; // false
|
||||
```
|
||||
|
||||
**JSON.stringify**
|
||||
### JSON.stringify
|
||||
|
||||
A common solution that many people suggest is to use `JSON.stringify()`, which allows us to serialize each array and then compare the two serialized strings. A simple implementation of this might look something like this:
|
||||
|
||||
@ -45,7 +45,7 @@ equals([null], [undefined]); // true, should be false
|
||||
|
||||
While these cases seem rather uncommon, they might cause some very annoying issues that are hard to track down and fix, which is why this solution is not recommended for most use-cases.
|
||||
|
||||
**A better way**
|
||||
### A better way
|
||||
|
||||
A better approach would be to compare the two arrays' `length`s and use `Array.prototype.every()` to compare the values of the two:
|
||||
|
||||
@ -66,7 +66,7 @@ equals([null], [undefined]); // false
|
||||
|
||||
This approach safeguards against the serialization issue described above, however it does not take into account nested arrays or objects, which need to be checked recursively. For a robust solution that handles this and other issues, you should use the [equals snippet](/js/s/equals).
|
||||
|
||||
**Comparing out of order**
|
||||
### Comparing out of order
|
||||
|
||||
Finally, there are cases where the order of the elements in each array is not important and we only care about the same values existing in both arrays. For these cases, you can use `Set` and `Array.prototype.filter()` in combination with a loop to iterate over unique values and check if each one appears the same amount of times in each array:
|
||||
|
||||
|
||||
Reference in New Issue
Block a user