DEV Community

Cover image for How to compare two arrays in Javascript
Tiziano Cappai
Tiziano Cappai

Posted on

How to compare two arrays in Javascript

How many times have you found yourself having to verify if the contents of two arrays were equal? (It happens to me often)

Now I’ll show you two ways to solve this problem:

First approach: using JSON.stringify(), see more here

// `a` and `b` are arrays
const isEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b);

// Examples
isEqual([1, 2, 3], [1, 2, 3]); // true
isEqual([1, 2, 3], [1, '2', 3]); // false
Enter fullscreen mode Exit fullscreen mode

Second approach using every(), see more here

// `a` and `b` are arrays
const isEqual = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
// Examples
isEqual([1, 2, 3], [1, 2, 3]); // true
isEqual([1, 2, 3], [1, '2', 3]); // false
Enter fullscreen mode Exit fullscreen mode

That's all, hope you re enjoining it! 🙂

Want to connect? Reach out to me on LinkedIn

Top comments (0)