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
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
That's all, hope you re enjoining it! 🙂
Want to connect? Reach out to me on LinkedIn
Top comments (0)