DEV Community

Cover image for Compare two arrays - JavaScript
syedsimanta03
syedsimanta03

Posted on

Compare two arrays - JavaScript

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

// Or
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

Top comments (1)

Collapse
 
chaugiang profile image
Nguyen Tran Chau Giang • Edited

Try this:

For 1st:

isEqual([()=>{}],[()=>{2}]) isEqual([NaN],[null]) //.... // expect false but true 
Enter fullscreen mode Exit fullscreen mode

For 2nd:

isEqual([NaN],[NaN]) // what is your expectation? 
Enter fullscreen mode Exit fullscreen mode