diff --git a/snippets/closest.md b/snippets/closest.md new file mode 100644 index 000000000..d8d732dbd --- /dev/null +++ b/snippets/closest.md @@ -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 +``` diff --git a/snippets/findConsecutive.md b/snippets/findConsecutive.md new file mode 100644 index 000000000..3370cc447 --- /dev/null +++ b/snippets/findConsecutive.md @@ -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]] +``` diff --git a/snippets/ranking.md b/snippets/ranking.md new file mode 100644 index 000000000..cacd33da7 --- /dev/null +++ b/snippets/ranking.md @@ -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] +``` diff --git a/snippets/transpose.md b/snippets/transpose.md new file mode 100644 index 000000000..d55112d8a --- /dev/null +++ b/snippets/transpose.md @@ -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] +```