Add 4 array snippets

This commit is contained in:
Chalarangelo
2022-03-28 11:36:11 +03:00
parent bc76b1169f
commit 003b4b21d0
4 changed files with 86 additions and 0 deletions

21
snippets/closest.md Normal file
View File

@ -0,0 +1,21 @@
---
title: Closest numeric match
tags: math,array
expertise: intermediate
author: chalarangelo
firstSeen: 2022-03-30T05:00:00-04:00
---
Finds the closest number from an array.
- Use `Array.prototype.reduce()` to scan all elements of the array.
- Use `Math.abs()` to compare each element's distance from the target value, storing the closest match.
```js
const closest = (arr, n) =>
arr.reduce((acc, num) => (Math.abs(num - n) < Math.abs(acc - n) ? num : acc));
```
```js
closest([6, 1, 3, 7, 9], 5); // 6
```

View File

@ -0,0 +1,22 @@
---
title: Arrays of consecutive elements
tags: array
expertise: intermediate
author: chalarangelo
firstSeen: 2022-04-06T05:00:00-04:00
---
Finds all arrays of consecutive elements.
- Use `Array.prototype.slice()` to create an array with `n - 1` elements removed from the start.
- Use `Array.prototype.map()` and `Array.prototype.slice()` to map each element to an array of `n` consecutive elements.
```js
const findConsecutive = (arr, n) =>
arr.slice(n - 1).map((v, i) => arr.slice(i, i + n));
```
```js
findConsecutive([1, 2, 3, 4, 5], 2);
// [[1, 2], [2, 3], [3, 4], [4, 5]]
```

23
snippets/ranking.md Normal file
View File

@ -0,0 +1,23 @@
---
title: Array ranking
tags: array,math
expertise: intermediate
author: chalarangelo
firstSeen: 2022-04-13T05:00:00-04:00
---
Calculates the ranking of an array based on a comparator function.
- Use `Array.prototype.map()` and `Array.prototype.filter()` to map each element to a rank using the provided comparator function.
```js
const ranking = (arr, compFn) =>
arr.map(a => arr.filter(b => compFn(a, b)).length + 1);
```
```js
ranking([8, 6, 9, 5], (a, b) => a < b);
// [2, 3, 1, 4]
ranking(['c', 'a', 'b', 'd'], (a, b) => a.localeCompare(b) > 0);
// [3, 1, 2, 4]
```

20
snippets/transpose.md Normal file
View File

@ -0,0 +1,20 @@
---
title: Transpose matrix
tags: array
expertise: intermediate
author: chalarangelo
firstSeen: 2022-04-20T05:00:00-04:00
---
Transposes a two-dimensional array.
- Use `Array.prototype.map()` to create the transpose of the given two-dimensional array.
```js
const transpose = arr => arr[0].map((col, i) => arr.map(row => row[i]));
```
```js
transpose([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]);
// [[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]
```