Add 7 new snippets

This commit is contained in:
Angelos Chalaris
2023-01-01 23:16:49 +02:00
parent 31a1b02cef
commit a4874b6b68
7 changed files with 198 additions and 0 deletions

24
snippets/intersects.md Normal file
View File

@ -0,0 +1,24 @@
---
title: Check if two arrays intersect
tags: array
author: chalarangelo
cover: blog_images/interior-5.jpg
firstSeen: 2023-02-17T05:00:00-04:00
---
Determines if two arrays have a common item.
- Create a `Set` from `b` to get the unique values in `b`.
- Use `Array.prototype.some()` on `a` to check if any of its values are contained in `b`, using `Set.prototype.has()`.
```js
const intersects = (a, b) => {
const s = new Set(b);
return [...new Set(a)].some(x => s.has(x));
};
```
```js
intersects(['a', 'b'], ['b', 'c']); // true
intersects(['a', 'b'], ['c', 'd']); // false
```