Add haveSameContents snippet

This commit is contained in:
Angelos Chalaris
2020-01-05 21:40:39 +02:00
parent 27ecf5fd86
commit 9a3e74cefa
2 changed files with 40 additions and 0 deletions

View File

@ -0,0 +1,23 @@
---
title: haveSameContents
tags: array,intermediate
---
Returns `true` if two arrays contain the same elements regardless of order, `false` otherwise.
Use a `for...of` loop over a `Set` created from the values of both arrays.
Use `Array.prototype.filter()` to compare the amount of occurences of each distinct value in both arrays.
Return `false` if the counts do not match for any element, `true` otherwise.
```js
const haveSameContents = (a, b) => {
for (const v of new Set([...a, ...b]))
if (a.filter(e => e === v).length !== b.filter(e => e === v).length)
return false;
return true;
}
```
```js
haveSameContents([1, 2, 4], [2, 4, 1]); // true
```