Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add snippet to compare two javascript arrays for equality #205

Merged
merged 9 commits into from
Jan 17, 2025
32 changes: 32 additions & 0 deletions snippets/javascript/array-manipulation/compare-arrays.md
Mathys-Gasnier marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
---
title: Compare Arrays
description: Deeply compares two arrays to check if they are equal to each other (supports nested arrays and objects).
author: KCSquid
tags: array,object,compare,equal
---

```js
const compareArrays = (a, b) => {
if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;
return a.every((v, i) =>
Array.isArray(v) && Array.isArray(b[i]) ? compareArrays(v, b[i]) :
typeof v === "object" && typeof b[i] === "object" ? compareObjects(v, b[i]) :
v === b[i]
);
};

const compareObjects = (a, b) => {
if (typeof a !== "object" || typeof b !== "object" || Object.keys(a).length !== Object.keys(b).length) return false;
return Object.keys(a).every(k =>
Array.isArray(a[k]) && Array.isArray(b[k]) ? compareArrays(a[k], b[k]) :
typeof a[k] === "object" && typeof b[k] === "object" ? compareObjects(a[k], b[k]) :
a[k] === b[k]
);
};

// Usage:
compareArrays([1, 2, 3], [1, 2, 3]); // Returns: true
compareArrays([1, 2, 3], [3, 2, 1]); // Returns: false
compareArrays([{a:1}], [{a:1}]); // Returns: true
compareArrays([{a:1}], null); // Returns: false
```
Loading