29 lines
812 B
Markdown
29 lines
812 B
Markdown
---
|
|
title: Check if arrays have same contents
|
|
tags: array
|
|
expertise: intermediate
|
|
author: chalarangelo
|
|
cover: blog_images/interior-15.jpg
|
|
firstSeen: 2020-01-05T21:40:39+02:00
|
|
lastUpdated: 2020-10-19T22:49:51+03:00
|
|
---
|
|
|
|
Checks if two arrays contain the same elements regardless of order.
|
|
|
|
- Use a `for...of` loop over a `Set` created from the values of both arrays.
|
|
- Use `Array.prototype.filter()` to compare the amount of occurrences 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
|
|
```
|