compare two arrays javascript
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
javascript compare arrays
Example 1
const a = [1, 2, 3]; const b = [1, 2, 3]; a === b; // false
compare arrays javascript
let names = ['Angel', 'Brian', 'Daniel']; let fruits = ['apples', 'bananas', 'carrots']; names === fruits; // false
JSON.stringify
- Use
JSON.stringify()
, which allows us to serialize each array and then compare the two serialized strings.
javascript compare two arrays
import {isEqual} from "lodash"; const isTwoArraysEqual = isEqual(array1, array2);
const equals = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]); const a = [1, 2, 3]; const b = [1, 2, 3]; const str = 'a'; const strObj = new String('a'); console.log(equals(a, b)); // true console.log(equals([str], [strObj])); // false console.log(equals([null], [undefined])); // false
comparing arrays javascript
const equals = (a, b) => JSON.stringify(a) === JSON.stringify(b); const a = [1, 2, 3]; const b = [1, 2, 3]; equals(a, b); // true