How to Compare Two Arrays in Javascript
I recently came across a situation where I needed to compare two arrays in Javascript. I was confused why my comparison returned false
, so I created a quick console log test.
console.log([0] === [0]) // false
I struggled to understand this for a moment. I remembered that almost everything in Javascript is a function or an object and an array is just an object which inherits from Array
with some special methods.
There isn't an 'equal' method for Javascript arrays. I'll do a separate post on this.
We can compare two arrays in Javascript by converting them to strings.
console.log(JSON.stringify([0]) === JSON.stringify([0])) // true
This works for a basic example. What if the items in the array are in a different order?
a = ['test', 'test2', 'test3']
b = ['test', 'test3', 'test2']
console.log(JSON.stringify(a) === JSON.stringify(b)) // false
We'll have to sort them both before converting them to strings.
a = ['test', 'test2', 'test3']
b = ['test', 'test3', 'test2']
console.log(JSON.stringify(a.sort()) === JSON.stringify(b.sort())) // true
Let's make this more useable.
a = ['test', 'test2', 'test3']
b = ['test', 'test3', 'test2']
const equal = (a, b) => {
return JSON.stringify(a.sort()) === JSON.stringify(b.sort())
}
console.log(equal(a, b))
Some things in Javascript aren't as easy as you'd expect. Now you know how to compare two arrays in Javascript.
tagged
share
Join the mailing list to get new articles straight to your inbox.
No spam, sales or ads. Unsubscribe any time.