From b3f7c855ff19700db7ff148cc045a207aa682b79 Mon Sep 17 00:00:00 2001 From: sabareesh Date: Thu, 14 Dec 2017 16:51:34 +0530 Subject: [PATCH 01/32] lodash remove duplicated --- README.md | 14 ++++++++++++++ snippets/remove.md | 12 ++++++++++++ 2 files changed, 26 insertions(+) create mode 100644 snippets/remove.md diff --git a/README.md b/README.md index 77a5233e9..eacb3932a 100644 --- a/README.md +++ b/README.md @@ -59,6 +59,7 @@ * [Random number in range](#random-number-in-range) * [Randomize order of array](#randomize-order-of-array) * [Redirect to url](#redirect-to-url) +* [Remove](#remove) * [Reverse a string](#reverse-a-string) * [RGB to hexadecimal](#rgb-to-hexadecimal) * [Run promises in series](#run-promises-in-series) @@ -610,6 +611,19 @@ const redirect = (url, asLink = true) => // redirect('https://google.com') ``` +### Remove + +Remove elements from `arr` that are returns truthy. Use `Array.filter()` to finding the matching elements and `Array.reduce()` to remove elements using `Array.splice()`.The `func` is invoked with three arguments: (value, index, array). + +```js +const remove = (arr, func) => + arr.filter(func).reduce((acc, val) => { + arr.splice(arr.indexOf(val), 1) + return acc.concat(val); + }, []) +//remove([1, 2, 3, 4], n => n % 2 == 0) -> [2, 4] +``` + ### Reverse a string Use array destructuring and `Array.reverse()` to reverse the order of the characters in the string. diff --git a/snippets/remove.md b/snippets/remove.md new file mode 100644 index 000000000..6c8e71d55 --- /dev/null +++ b/snippets/remove.md @@ -0,0 +1,12 @@ +### Remove + +Remove elements from `arr` that are returns truthy. Use `Array.filter()` to finding the matching elements and `Array.reduce()` to remove elements using `Array.splice()`.The `func` is invoked with three arguments: (value, index, array). + +```js +const remove = (arr, func) => + arr.filter(func).reduce((acc, val) => { + arr.splice(arr.indexOf(val), 1) + return acc.concat(val); + }, []) +//remove([1, 2, 3, 4], n => n % 2 == 0) -> [2, 4] +``` From a0409dbfaab355192a4355bfde48486673ea22e5 Mon Sep 17 00:00:00 2001 From: sabareesh Date: Thu, 14 Dec 2017 16:56:32 +0530 Subject: [PATCH 02/32] lodash remove duplicated --- README.md | 4 ---- 1 file changed, 4 deletions(-) diff --git a/README.md b/README.md index c8a19046c..12e86b020 100644 --- a/README.md +++ b/README.md @@ -57,13 +57,9 @@ * [Promisify](#promisify) * [Random integer in range](#random-integer-in-range) * [Random number in range](#random-number-in-range) -<<<<<<< HEAD * [Randomize order of array](#randomize-order-of-array) * [Redirect to url](#redirect-to-url) * [Remove](#remove) -======= -* [Redirect to URL](#redirect-to-url) ->>>>>>> 10ae7ad867aaa94d27da81180760d6a0fa84a3a8 * [Reverse a string](#reverse-a-string) * [RGB to hexadecimal](#rgb-to-hexadecimal) * [Run promises in series](#run-promises-in-series) From 2d7d447931a9414765a27583cb1cca2cb4c89a48 Mon Sep 17 00:00:00 2001 From: iamsoorena Date: Thu, 14 Dec 2017 18:00:15 +0330 Subject: [PATCH 03/32] add json to file function --- snippets/write-json-to-file.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 snippets/write-json-to-file.md diff --git a/snippets/write-json-to-file.md b/snippets/write-json-to-file.md new file mode 100644 index 000000000..6a0ae21a0 --- /dev/null +++ b/snippets/write-json-to-file.md @@ -0,0 +1,9 @@ +### Write a JSON to a file + +Write a `json` object to a `.json` file. +```js +const fs = require('fs') + +const jsonToFile = (obj, filename) => fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 4)) +// jsonToFile({test: "is passed"}, 'testJsonFile') +``` From 2ba42b300457039dfdfccf26f38f1f31a6c1f1a5 Mon Sep 17 00:00:00 2001 From: iamsoorena Date: Thu, 14 Dec 2017 18:34:05 +0330 Subject: [PATCH 04/32] add a functions that deeply cleans json objects from unwanted keys --- snippets/json-cleaner.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 snippets/json-cleaner.md diff --git a/snippets/json-cleaner.md b/snippets/json-cleaner.md new file mode 100644 index 000000000..46ef745dc --- /dev/null +++ b/snippets/json-cleaner.md @@ -0,0 +1,20 @@ +### Clean Json objects + +Clean your json object from unwanted keys, deeply. +provide set of `keys` to keep and an indicator for `children` if there is any. + +```js +const cleanObj = (obj, keys = [], childIndicator) => { + Object.keys(obj).forEach(key => { + if (key === childIndicator) { + cleanObj(obj[key], keys, childIndicator) + } else if (!keys.includes(key)) { + delete obj[key] + } + }) +} +/* + dirtyObj = { a: 1, b: 2, children: {a: 1, b :2}} + let cleaned = cleanObj(dirtyObj, [a]) // { a: 1, children : { a: 1}} + */ +``` From cd5eb04c4f020cdd5cf1908656a93969ef4ac056 Mon Sep 17 00:00:00 2001 From: Justin Lee Date: Thu, 14 Dec 2017 14:44:38 -0800 Subject: [PATCH 05/32] Rewrote pipe such that the first function may have any arity. --- snippets/pipe.md | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/snippets/pipe.md b/snippets/pipe.md index c61ec042c..11803210c 100644 --- a/snippets/pipe.md +++ b/snippets/pipe.md @@ -1,8 +1,18 @@ ### Pipe -Use `Array.reduce()` to pass value through functions. +Use `Array.reduce()` to perform left-to-right function composition. The first (leftmost) function can accept one or more arguments; the remaining functions must be unary. ```js -const pipe = (...funcs) => arg => funcs.reduce((acc, func) => func(acc), arg); -// pipe(btoa, x => x.toUpperCase())("Test") -> "VGVZDA==" +const pipe = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args))) +/* +const add5 = (x) => x + 5 +const multiply = (x, y) => x * y + +const multiplyAndAdd5 = pipe( + multiply, + add5 +) + +multiplyAndAdd5(5, 2) -> 15 +*/ ``` From b7d49126d7cec0e88851d1311c7d07c7178b214b Mon Sep 17 00:00:00 2001 From: Justin Lee Date: Thu, 14 Dec 2017 14:52:25 -0800 Subject: [PATCH 06/32] removed unnecessary brackets around one parameter function --- snippets/pipe.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/snippets/pipe.md b/snippets/pipe.md index 11803210c..9c13f5e27 100644 --- a/snippets/pipe.md +++ b/snippets/pipe.md @@ -5,7 +5,7 @@ Use `Array.reduce()` to perform left-to-right function composition. The first (l ```js const pipe = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args))) /* -const add5 = (x) => x + 5 +const add5 = x => x + 5 const multiply = (x, y) => x * y const multiplyAndAdd5 = pipe( From 807cd9913745cb82b8e085e9dc2ec5ea90ae5784 Mon Sep 17 00:00:00 2001 From: Justin Lee Date: Thu, 14 Dec 2017 14:53:20 -0800 Subject: [PATCH 07/32] Placed parameters of pipe on one line for better readability --- snippets/pipe.md | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/snippets/pipe.md b/snippets/pipe.md index 9c13f5e27..f46a32148 100644 --- a/snippets/pipe.md +++ b/snippets/pipe.md @@ -8,10 +8,7 @@ const pipe = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args))) const add5 = x => x + 5 const multiply = (x, y) => x * y -const multiplyAndAdd5 = pipe( - multiply, - add5 -) +const multiplyAndAdd5 = pipe(multiply, add5) multiplyAndAdd5(5, 2) -> 15 */ From 565c5e6a66aad71fab0b2ae0143a2c2e7c63741b Mon Sep 17 00:00:00 2001 From: taltmann42 Date: Thu, 14 Dec 2017 23:54:55 +0100 Subject: [PATCH 08/32] Array zip Zip method from https://lodash.com/docs/4.17.4#zip --- snippets/array-zip.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 snippets/array-zip.md diff --git a/snippets/array-zip.md b/snippets/array-zip.md new file mode 100644 index 000000000..d63f79b15 --- /dev/null +++ b/snippets/array-zip.md @@ -0,0 +1,17 @@ +### Array zip + +Use `Math.max.apply` to get the longest array in the arguments. +Creates an array with that length as return value and use `Array.from` with a map-function to create an array of grouped elements. +If lengths of the argument-arrays vary, `undefined` is used where no value could be found. + +```js +const zip = (...arrays) => { + const maxLength = Math.max.apply(null, arrays.map(a => a.length)); + return Array.from({length: maxLength}).map((_, i) => { + return Array.from({length: arrays.length}, (_, k) => arrays[k][i]) + }) +} + +//zip(['a', 'b'], [1, 2], [true, false]); -> [['a', 1, true], ['b', 2, false]] +zip(['a'], [1, 2], [true, false]); -> [['a', 1, true], [undefined, 2, false]] +``` From a4c7673ec272ea5f7104ff303aeedee7c332be92 Mon Sep 17 00:00:00 2001 From: taltmann42 Date: Thu, 14 Dec 2017 23:56:51 +0100 Subject: [PATCH 09/32] Update array-zip.md --- snippets/array-zip.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/snippets/array-zip.md b/snippets/array-zip.md index d63f79b15..08c40ed68 100644 --- a/snippets/array-zip.md +++ b/snippets/array-zip.md @@ -13,5 +13,5 @@ const zip = (...arrays) => { } //zip(['a', 'b'], [1, 2], [true, false]); -> [['a', 1, true], ['b', 2, false]] -zip(['a'], [1, 2], [true, false]); -> [['a', 1, true], [undefined, 2, false]] +//zip(['a'], [1, 2], [true, false]); -> [['a', 1, true], [undefined, 2, false]] ``` From 699bda348de95f7b3aae660c5a3aa7a3216818b4 Mon Sep 17 00:00:00 2001 From: taltmann42 Date: Fri, 15 Dec 2017 00:23:10 +0100 Subject: [PATCH 10/32] Create array-without.md --- snippets/array-without.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 snippets/array-without.md diff --git a/snippets/array-without.md b/snippets/array-without.md new file mode 100644 index 000000000..353d1308e --- /dev/null +++ b/snippets/array-without.md @@ -0,0 +1,9 @@ +### Array without + +Filters out array elements if they are included in the given `values` arguments + +```js +const without = ((arr, ...values) => arr.filter(x => !values.includes(x))) + +//without([2, 1, 2, 3], 1, 2); -> [3] +``` From 88fc66efd657e28f30c990236852936fe36594d1 Mon Sep 17 00:00:00 2001 From: taltmann42 Date: Fri, 15 Dec 2017 00:30:18 +0100 Subject: [PATCH 11/32] Delete array-without.md --- snippets/array-without.md | 9 --------- 1 file changed, 9 deletions(-) delete mode 100644 snippets/array-without.md diff --git a/snippets/array-without.md b/snippets/array-without.md deleted file mode 100644 index 353d1308e..000000000 --- a/snippets/array-without.md +++ /dev/null @@ -1,9 +0,0 @@ -### Array without - -Filters out array elements if they are included in the given `values` arguments - -```js -const without = ((arr, ...values) => arr.filter(x => !values.includes(x))) - -//without([2, 1, 2, 3], 1, 2); -> [3] -``` From f567e5979bcc468c0a6faa03ea55ed851f0da5f4 Mon Sep 17 00:00:00 2001 From: King Date: Thu, 14 Dec 2017 19:00:10 -0500 Subject: [PATCH 12/32] add takeRight --- snippets/takeRight.md | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 snippets/takeRight.md diff --git a/snippets/takeRight.md b/snippets/takeRight.md new file mode 100644 index 000000000..03fc634fa --- /dev/null +++ b/snippets/takeRight.md @@ -0,0 +1,10 @@ +### takeRight + +Use `Array.slice()` to create a slice of the array with `n` elements taken from the end. + +```js +const takeRight = (arr, n = 1) => arr.slice(arr.length - n, arr.length); +// takeRight([1, 2, 3], 2) -> [ 2, 3 ] +// takeRight([1, 2, 3]) -> [3] +// takeRight([1, 2, 3]) -> [] +``` \ No newline at end of file From e46b72ca13a7175b8d0c2659e05690dd3d931012 Mon Sep 17 00:00:00 2001 From: King Date: Thu, 14 Dec 2017 19:03:20 -0500 Subject: [PATCH 13/32] ran npm run tagger & add array tag for takeRight --- tag_database | 1 + 1 file changed, 1 insertion(+) diff --git a/tag_database b/tag_database index b2535a484..a174c20c3 100644 --- a/tag_database +++ b/tag_database @@ -78,6 +78,7 @@ sum-of-array-of-numbers:array swap-values-of-two-variables:utility tail-of-list:array take:array +takeRight:array truncate-a-string:string unique-values-of-array:array URL-parameters:utility From dc929505c64053bdc85e7adad1f6010f31a55325 Mon Sep 17 00:00:00 2001 From: sabareesh Date: Fri, 15 Dec 2017 11:41:51 +0530 Subject: [PATCH 14/32] new arrray remove and concat issue fixed --- README.md | 13 ++++++++++++- snippets/array-concatenation.md | 2 +- snippets/remove.md | 2 ++ 3 files changed, 15 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 12e86b020..35db7870c 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,7 @@ ## Contents * [Anagrams of string (with duplicates)](#anagrams-of-string-with-duplicates) +* [Array concatenation](#array-concatenation) * [Array difference](#array-difference) * [Array intersection](#array-intersection) * [Array union](#array-union) @@ -57,7 +58,6 @@ * [Promisify](#promisify) * [Random integer in range](#random-integer-in-range) * [Random number in range](#random-number-in-range) -* [Randomize order of array](#randomize-order-of-array) * [Redirect to url](#redirect-to-url) * [Remove](#remove) * [Reverse a string](#reverse-a-string) @@ -97,6 +97,15 @@ const anagrams = str => { // anagrams('abc') -> ['abc','acb','bac','bca','cab','cba'] ``` +### Array concatenation + +Use `Array.concat()` to concatenate and array with any additional arrays and/or values, specified in `args`. + +```js +const ArrayConcat = (arr, ...args) => [].concat(arr, ...args); +// ArrayConcat([1], [1, 2, 3, [4]]) -> [1, 2, 3, [4]] +``` + ### Array difference Create a `Set` from `b`, then use `Array.filter()` on `a` to only keep values not contained in `b`. @@ -618,10 +627,12 @@ Remove elements from `arr` that are returns truthy. Use `Array.filter()` to find ```js const remove = (arr, func) => + Array.isArray(arr) ? arr.filter(func).reduce((acc, val) => { arr.splice(arr.indexOf(val), 1) return acc.concat(val); }, []) + : []; //remove([1, 2, 3, 4], n => n % 2 == 0) -> [2, 4] ``` diff --git a/snippets/array-concatenation.md b/snippets/array-concatenation.md index 39d978d6e..f441a0a17 100644 --- a/snippets/array-concatenation.md +++ b/snippets/array-concatenation.md @@ -3,6 +3,6 @@ Use `Array.concat()` to concatenate and array with any additional arrays and/or values, specified in `args`. ```js -const ArrayConcat = (arr, ...args) => arr.concat(...args); +const ArrayConcat = (arr, ...args) => [].concat(arr, ...args); // ArrayConcat([1], [1, 2, 3, [4]]) -> [1, 2, 3, [4]] ``` diff --git a/snippets/remove.md b/snippets/remove.md index 6c8e71d55..0a25e6f00 100644 --- a/snippets/remove.md +++ b/snippets/remove.md @@ -4,9 +4,11 @@ Remove elements from `arr` that are returns truthy. Use `Array.filter()` to find ```js const remove = (arr, func) => + Array.isArray(arr) ? arr.filter(func).reduce((acc, val) => { arr.splice(arr.indexOf(val), 1) return acc.concat(val); }, []) + : []; //remove([1, 2, 3, 4], n => n % 2 == 0) -> [2, 4] ``` From efb72451fb15bff404c3073fe80049ecd1746f36 Mon Sep 17 00:00:00 2001 From: xaveyaguarez Date: Thu, 14 Dec 2017 22:34:10 -0800 Subject: [PATCH 15/32] deep flatten array without reduce --- snippets/deep-flatten-array.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/snippets/deep-flatten-array.md b/snippets/deep-flatten-array.md index c350d848c..1dffe860f 100644 --- a/snippets/deep-flatten-array.md +++ b/snippets/deep-flatten-array.md @@ -1,10 +1,9 @@ ### Deep flatten array Use recursion. -Use `Array.reduce()` to get all elements that are not arrays, flatten each element that is an array. +Use `[].concat()` and the spread operator `...` to flatten an array, and recursively flatten each element that is an array. ```js -const deepFlatten = arr => - arr.reduce((a, v) => a.concat(Array.isArray(v) ? deepFlatten(v) : v), []); +const deepFlatten = arr => [].concat(...arr.map(v => Array.isArray(v) ? deepFlatten(v) : v)); // deepFlatten([1,[2],[[3],4],5]) -> [1,2,3,4,5] ``` From ea8c27e7c154a80a118c610886550b20900a1580 Mon Sep 17 00:00:00 2001 From: King Date: Fri, 15 Dec 2017 02:35:30 -0500 Subject: [PATCH 16/32] add without.md --- snippets/without.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 snippets/without.md diff --git a/snippets/without.md b/snippets/without.md new file mode 100644 index 000000000..00876b5c9 --- /dev/null +++ b/snippets/without.md @@ -0,0 +1,12 @@ +### Without + +Use `Array.filter()` to create an array excluding all given values + +```js + +const without = (arr, ...args) => arr.filter(v => args.indexOf(v) === -1) + +// without[2, 1, 2, 3], 1, 2) -> [3] +// without([2, 1, 2, 3, 4, 5, 5, 5, 3, 2, 7, 7], 3, 1, 5, 2) -> [ 4, 7, 7 ] + +``` From 94096b9de4754a6917bf789db0f742df7815f6a6 Mon Sep 17 00:00:00 2001 From: King Date: Fri, 15 Dec 2017 02:37:19 -0500 Subject: [PATCH 17/32] ran npm run tagger & add array tag to DB --- tag_database | 1 + 1 file changed, 1 insertion(+) diff --git a/tag_database b/tag_database index b2535a484..937676886 100644 --- a/tag_database +++ b/tag_database @@ -85,3 +85,4 @@ UUID-generator:utility validate-email:utility validate-number:utility value-or-default:utility +without:array From e86c1eaf3a1123e510a4d3c096c2f4c4097f6549 Mon Sep 17 00:00:00 2001 From: Arjun Mahishi Date: Fri, 15 Dec 2017 13:45:12 +0530 Subject: [PATCH 18/32] Added snippet to sample an array --- snippets/array-sample.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 snippets/array-sample.md diff --git a/snippets/array-sample.md b/snippets/array-sample.md new file mode 100644 index 000000000..d48f13840 --- /dev/null +++ b/snippets/array-sample.md @@ -0,0 +1,9 @@ +### Array sample + +Use `Math.random()` to generate a random number, multiply it with `Array.length` and round it of to the nearest whole number using `Math.floor()`. Works with strings too. + +```js +const sample = arr => arr[Math.floor(Math.random() * arr.length)]; + +// sample([3, 7, 9, 11]) -> 9 +``` \ No newline at end of file From 129f31e08de63c69adaa63bbc98dddd4c0052fd6 Mon Sep 17 00:00:00 2001 From: fpluquet Date: Fri, 15 Dec 2017 09:47:57 +0100 Subject: [PATCH 19/32] Update chunk-array.md Fix chunk array result --- snippets/chunk-array.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/snippets/chunk-array.md b/snippets/chunk-array.md index c14bf269d..ba3e5e42e 100644 --- a/snippets/chunk-array.md +++ b/snippets/chunk-array.md @@ -7,5 +7,5 @@ If the original array can't be split evenly, the final chunk will contain the re ```js const chunk = (arr, size) => Array.from({length: Math.ceil(arr.length / size)}, (v, i) => arr.slice(i * size, i * size + size)); -// chunk([1,2,3,4,5], 2) -> [[1,2],[3,4],5] +// chunk([1,2,3,4,5], 2) -> [[1,2],[3,4],[5]] ``` From fbfd5ebd467bf68f0e15e0261f5b266e7f1a8727 Mon Sep 17 00:00:00 2001 From: iamsoorena Date: Fri, 15 Dec 2017 12:56:13 +0330 Subject: [PATCH 20/32] removing unrelated file from "to merge" branch --- snippets/json-cleaner.md | 20 -------------------- 1 file changed, 20 deletions(-) delete mode 100644 snippets/json-cleaner.md diff --git a/snippets/json-cleaner.md b/snippets/json-cleaner.md deleted file mode 100644 index 46ef745dc..000000000 --- a/snippets/json-cleaner.md +++ /dev/null @@ -1,20 +0,0 @@ -### Clean Json objects - -Clean your json object from unwanted keys, deeply. -provide set of `keys` to keep and an indicator for `children` if there is any. - -```js -const cleanObj = (obj, keys = [], childIndicator) => { - Object.keys(obj).forEach(key => { - if (key === childIndicator) { - cleanObj(obj[key], keys, childIndicator) - } else if (!keys.includes(key)) { - delete obj[key] - } - }) -} -/* - dirtyObj = { a: 1, b: 2, children: {a: 1, b :2}} - let cleaned = cleanObj(dirtyObj, [a]) // { a: 1, children : { a: 1}} - */ -``` From 6bf02367311da313dffb0d3e36112cf2d4c81342 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Fri, 15 Dec 2017 12:53:09 +0200 Subject: [PATCH 21/32] Tag, lint, build --- README.md | 79 +++++++++++++++++++++-- snippets/array-sample.md | 8 +-- snippets/{without.md => array-without.md} | 9 +-- snippets/array-zip.md | 7 +- snippets/deep-flatten-array.md | 3 +- snippets/pipe.md | 9 ++- snippets/{takeRight.md => take-right.md} | 5 +- tag_database | 6 +- 8 files changed, 94 insertions(+), 32 deletions(-) rename snippets/{without.md => array-without.md} (88%) rename snippets/{takeRight.md => take-right.md} (83%) diff --git a/README.md b/README.md index 7160b9afb..b8412a802 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,10 @@ * [Array concatenation](#array-concatenation) * [Array difference](#array-difference) * [Array intersection](#array-intersection) +* [Array sample](#array-sample) * [Array union](#array-union) +* [Array without](#array-without) +* [Array zip](#array-zip) * [Average of array of numbers](#average-of-array-of-numbers) * [Chunk array](#chunk-array) * [Compact](#compact) @@ -39,6 +42,7 @@ * [Similarity between arrays](#similarity-between-arrays) * [Sum of array of numbers](#sum-of-array-of-numbers) * [Tail of list](#tail-of-list) +* [Take right](#take-right) * [Take](#take) * [Unique values of array](#unique-values-of-array) @@ -149,6 +153,18 @@ const intersection = (a, b) => { const s = new Set(b); return a.filter(x => s.ha [⬆ back to top](#table-of-contents) +### Array sample + +Use `Math.random()` to generate a random number, multiply it with `length` and round it of to the nearest whole number using `Math.floor()`. +This method also works with strings. + +```js +const sample = arr => arr[Math.floor(Math.random() * arr.length)]; +// sample([3, 7, 9, 11]) -> 9 +``` + +[⬆ back to top](#table-of-contents) + ### Array union Create a `Set` with all values of `a` and `b` and convert to an array. @@ -160,6 +176,37 @@ const union = (a, b) => Array.from(new Set([...a, ...b])); [⬆ back to top](#table-of-contents) +### Array without + +Use `Array.filter()` to create an array excluding all given values. + +```js +const without = (arr, ...args) => arr.filter(v => args.indexOf(v) === -1); +// without[2, 1, 2, 3], 1, 2) -> [3] +// without([2, 1, 2, 3, 4, 5, 5, 5, 3, 2, 7, 7], 3, 1, 5, 2) -> [ 4, 7, 7 ] +``` + +[⬆ back to top](#table-of-contents) + +### Array zip + +Use `Math.max.apply()` to get the longest array in the arguments. +Creates an array with that length as return value and use `Array.from()` with a map-function to create an array of grouped elements. +If lengths of the argument-arrays vary, `undefined` is used where no value could be found. + +```js +const zip = (...arrays) => { + const maxLength = Math.max.apply(null, arrays.map(a => a.length)); + return Array.from({length: maxLength}).map((_, i) => { + return Array.from({length: arrays.length}, (_, k) => arrays[k][i]); + }) +} +//zip(['a', 'b'], [1, 2], [true, false]); -> [['a', 1, true], ['b', 2, false]] +//zip(['a'], [1, 2], [true, false]); -> [['a', 1, true], [undefined, 2, false]] +``` + +[⬆ back to top](#table-of-contents) + ### Average of array of numbers Use `Array.reduce()` to add each value to an accumulator, initialized with a value of `0`, divide by the `length` of the array. @@ -180,7 +227,7 @@ If the original array can't be split evenly, the final chunk will contain the re ```js const chunk = (arr, size) => Array.from({length: Math.ceil(arr.length / size)}, (v, i) => arr.slice(i * size, i * size + size)); -// chunk([1,2,3,4,5], 2) -> [[1,2],[3,4],5] +// chunk([1,2,3,4,5], 2) -> [[1,2],[3,4],[5]] ``` [⬆ back to top](#table-of-contents) @@ -210,11 +257,11 @@ const countOccurrences = (arr, value) => arr.reduce((a, v) => v === value ? a + ### Deep flatten array Use recursion. -Use `Array.reduce()` to get all elements that are not arrays, flatten each element that is an array. +Use `Array.concat()` with an empty array (`[]`) and the spread operator (`...`) to flatten an array. +Rrecursively flatten each element that is an array. ```js -const deepFlatten = arr => - arr.reduce((a, v) => a.concat(Array.isArray(v) ? deepFlatten(v) : v), []); +const deepFlatten = arr => [].concat(...arr.map(v => Array.isArray(v) ? deepFlatten(v) : v)); // deepFlatten([1,[2],[[3],4],5]) -> [1,2,3,4,5] ``` @@ -469,6 +516,18 @@ const tail = arr => arr.length > 1 ? arr.slice(1) : arr; [⬆ back to top](#table-of-contents) +### Take right + +Use `Array.slice()` to create a slice of the array with `n` elements taken from the end. + +```js +const takeRight = (arr, n = 1) => arr.slice(arr.length - n, arr.length); +// takeRight([1, 2, 3], 2) -> [ 2, 3 ] +// takeRight([1, 2, 3]) -> [3] +``` + +[⬆ back to top](#table-of-contents) + ### Take Use `Array.slice()` to create a slice of the array with `n` elements taken from the beginning. @@ -633,11 +692,17 @@ const curry = (fn, arity = fn.length, ...args) => ### Pipe -Use `Array.reduce()` to pass value through functions. +Use `Array.reduce()` to perform left-to-right function composition. +The first (leftmost) function can accept one or more arguments; the remaining functions must be unary. ```js -const pipe = (...funcs) => arg => funcs.reduce((acc, func) => func(acc), arg); -// pipe(btoa, x => x.toUpperCase())("Test") -> "VGVZDA==" +const pipe = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args))); +/* +const add5 = x => x + 5 +const multiply = (x, y) => x * y +const multiplyAndAdd5 = pipe(multiply, add5) +multiplyAndAdd5(5, 2) -> 15 +*/ ``` [⬆ back to top](#table-of-contents) diff --git a/snippets/array-sample.md b/snippets/array-sample.md index d48f13840..9de5c5ae0 100644 --- a/snippets/array-sample.md +++ b/snippets/array-sample.md @@ -1,9 +1,9 @@ ### Array sample -Use `Math.random()` to generate a random number, multiply it with `Array.length` and round it of to the nearest whole number using `Math.floor()`. Works with strings too. +Use `Math.random()` to generate a random number, multiply it with `length` and round it of to the nearest whole number using `Math.floor()`. +This method also works with strings. ```js const sample = arr => arr[Math.floor(Math.random() * arr.length)]; - -// sample([3, 7, 9, 11]) -> 9 -``` \ No newline at end of file +// sample([3, 7, 9, 11]) -> 9 +``` diff --git a/snippets/without.md b/snippets/array-without.md similarity index 88% rename from snippets/without.md rename to snippets/array-without.md index 00876b5c9..dd657fe2a 100644 --- a/snippets/without.md +++ b/snippets/array-without.md @@ -1,12 +1,9 @@ -### Without +### Array without -Use `Array.filter()` to create an array excluding all given values +Use `Array.filter()` to create an array excluding all given values. ```js - -const without = (arr, ...args) => arr.filter(v => args.indexOf(v) === -1) - +const without = (arr, ...args) => arr.filter(v => args.indexOf(v) === -1); // without[2, 1, 2, 3], 1, 2) -> [3] // without([2, 1, 2, 3, 4, 5, 5, 5, 3, 2, 7, 7], 3, 1, 5, 2) -> [ 4, 7, 7 ] - ``` diff --git a/snippets/array-zip.md b/snippets/array-zip.md index 08c40ed68..6c9a2491b 100644 --- a/snippets/array-zip.md +++ b/snippets/array-zip.md @@ -1,17 +1,16 @@ ### Array zip -Use `Math.max.apply` to get the longest array in the arguments. -Creates an array with that length as return value and use `Array.from` with a map-function to create an array of grouped elements. +Use `Math.max.apply()` to get the longest array in the arguments. +Creates an array with that length as return value and use `Array.from()` with a map-function to create an array of grouped elements. If lengths of the argument-arrays vary, `undefined` is used where no value could be found. ```js const zip = (...arrays) => { const maxLength = Math.max.apply(null, arrays.map(a => a.length)); return Array.from({length: maxLength}).map((_, i) => { - return Array.from({length: arrays.length}, (_, k) => arrays[k][i]) + return Array.from({length: arrays.length}, (_, k) => arrays[k][i]); }) } - //zip(['a', 'b'], [1, 2], [true, false]); -> [['a', 1, true], ['b', 2, false]] //zip(['a'], [1, 2], [true, false]); -> [['a', 1, true], [undefined, 2, false]] ``` diff --git a/snippets/deep-flatten-array.md b/snippets/deep-flatten-array.md index 1dffe860f..d33ff7e25 100644 --- a/snippets/deep-flatten-array.md +++ b/snippets/deep-flatten-array.md @@ -1,7 +1,8 @@ ### Deep flatten array Use recursion. -Use `[].concat()` and the spread operator `...` to flatten an array, and recursively flatten each element that is an array. +Use `Array.concat()` with an empty array (`[]`) and the spread operator (`...`) to flatten an array. +Rrecursively flatten each element that is an array. ```js const deepFlatten = arr => [].concat(...arr.map(v => Array.isArray(v) ? deepFlatten(v) : v)); diff --git a/snippets/pipe.md b/snippets/pipe.md index f46a32148..e5136777b 100644 --- a/snippets/pipe.md +++ b/snippets/pipe.md @@ -1,15 +1,14 @@ ### Pipe -Use `Array.reduce()` to perform left-to-right function composition. The first (leftmost) function can accept one or more arguments; the remaining functions must be unary. +Use `Array.reduce()` to perform left-to-right function composition. +The first (leftmost) function can accept one or more arguments; the remaining functions must be unary. ```js -const pipe = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args))) +const pipe = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args))); /* const add5 = x => x + 5 -const multiply = (x, y) => x * y - +const multiply = (x, y) => x * y const multiplyAndAdd5 = pipe(multiply, add5) - multiplyAndAdd5(5, 2) -> 15 */ ``` diff --git a/snippets/takeRight.md b/snippets/take-right.md similarity index 83% rename from snippets/takeRight.md rename to snippets/take-right.md index 03fc634fa..1e7c55766 100644 --- a/snippets/takeRight.md +++ b/snippets/take-right.md @@ -1,4 +1,4 @@ -### takeRight +### Take right Use `Array.slice()` to create a slice of the array with `n` elements taken from the end. @@ -6,5 +6,4 @@ Use `Array.slice()` to create a slice of the array with `n` elements taken from const takeRight = (arr, n = 1) => arr.slice(arr.length - n, arr.length); // takeRight([1, 2, 3], 2) -> [ 2, 3 ] // takeRight([1, 2, 3]) -> [3] -// takeRight([1, 2, 3]) -> [] -``` \ No newline at end of file +``` diff --git a/tag_database b/tag_database index d1733c293..7e20b7516 100644 --- a/tag_database +++ b/tag_database @@ -2,7 +2,10 @@ anagrams-of-string-(with-duplicates):string array-concatenation:array array-difference:array array-intersection:array +array-sample:array array-union:array +array-without:array +array-zip:array average-of-array-of-numbers:array bottom-visible:browser capitalize-first-letter-of-every-word:string @@ -77,8 +80,8 @@ standard-deviation:math sum-of-array-of-numbers:array swap-values-of-two-variables:utility tail-of-list:array +take-right:array take:array -takeRight:array truncate-a-string:string unique-values-of-array:array URL-parameters:utility @@ -86,4 +89,3 @@ UUID-generator:utility validate-email:utility validate-number:utility value-or-default:utility -without:array From e8c2df84e22882ecfcd042d5ae68f44bc754ebc1 Mon Sep 17 00:00:00 2001 From: Arjun Mahishi Date: Fri, 15 Dec 2017 16:30:12 +0530 Subject: [PATCH 22/32] Added snippet for array includes --- snippets/array-includes.md | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 snippets/array-includes.md diff --git a/snippets/array-includes.md b/snippets/array-includes.md new file mode 100644 index 000000000..c068d17b2 --- /dev/null +++ b/snippets/array-includes.md @@ -0,0 +1,10 @@ +### Array includes + +Use `slice()` to offset the array/string. `Array.indexOf()` returns `-1` if the sub-string/array dosen't contain the given `value`. + +```js +const includes = (collection, val, fromIndex=0) => collection.slice(fromIndex).indexOf(val) != -1; + +// includes("30-seconds-of-code", "code") -> true +// includes([1, 2, 3, 4], [1, 2], 1) -> false +``` \ No newline at end of file From fa1c6b5755fa8e649aa1b48bfc23b880dca5a185 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Fri, 15 Dec 2017 13:06:53 +0200 Subject: [PATCH 23/32] Tag, lint, build --- README.md | 14 ++++++++++++++ snippets/array-includes.md | 6 +++--- tag_database | 1 + 3 files changed, 18 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index b8412a802..416266397 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,7 @@ ### Array * [Array concatenation](#array-concatenation) * [Array difference](#array-difference) +* [Array includes](#array-includes) * [Array intersection](#array-intersection) * [Array sample](#array-sample) * [Array union](#array-union) @@ -142,6 +143,19 @@ const difference = (a, b) => { const s = new Set(b); return a.filter(x => !s.has [⬆ back to top](#table-of-contents) +### Array includes + +Use `slice()` to offset the array/string and `indexOf()` to check if the value is included. +Omit the last argument, `fromIndex`, to check the whole array/string. + +```js +const includes = (collection, val, fromIndex=0) => collection.slice(fromIndex).indexOf(val) != -1; +// includes("30-seconds-of-code", "code") -> true +// includes([1, 2, 3, 4], [1, 2], 1) -> false +``` + +[⬆ back to top](#table-of-contents) + ### Array intersection Create a `Set` from `b`, then use `Array.filter()` on `a` to only keep values contained in `b`. diff --git a/snippets/array-includes.md b/snippets/array-includes.md index c068d17b2..5ebcbc009 100644 --- a/snippets/array-includes.md +++ b/snippets/array-includes.md @@ -1,10 +1,10 @@ ### Array includes -Use `slice()` to offset the array/string. `Array.indexOf()` returns `-1` if the sub-string/array dosen't contain the given `value`. +Use `slice()` to offset the array/string and `indexOf()` to check if the value is included. +Omit the last argument, `fromIndex`, to check the whole array/string. ```js const includes = (collection, val, fromIndex=0) => collection.slice(fromIndex).indexOf(val) != -1; - // includes("30-seconds-of-code", "code") -> true // includes([1, 2, 3, 4], [1, 2], 1) -> false -``` \ No newline at end of file +``` diff --git a/tag_database b/tag_database index 7e20b7516..67bdedd3c 100644 --- a/tag_database +++ b/tag_database @@ -1,6 +1,7 @@ anagrams-of-string-(with-duplicates):string array-concatenation:array array-difference:array +array-includes:array array-intersection:array array-sample:array array-union:array From 4d3a9bbcee681398ccb2cfa4d758f5bde3084fa5 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Fri, 15 Dec 2017 13:15:21 +0200 Subject: [PATCH 24/32] Update write-json-to-file.md --- snippets/write-json-to-file.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/snippets/write-json-to-file.md b/snippets/write-json-to-file.md index 6a0ae21a0..5cff72064 100644 --- a/snippets/write-json-to-file.md +++ b/snippets/write-json-to-file.md @@ -1,9 +1,9 @@ ### Write a JSON to a file -Write a `json` object to a `.json` file. -```js -const fs = require('fs') +Use `fs.writeFile()`, template literals and `JSON.stringify()` to write a `json` object to a `.json` file. -const jsonToFile = (obj, filename) => fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 4)) +```js +const fs = require('fs'); +const jsonToFile = (obj, filename) => fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2)) // jsonToFile({test: "is passed"}, 'testJsonFile') ``` From e34229c51f7d9b7f68eba50e07f545dbd3def4bc Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Fri, 15 Dec 2017 13:15:51 +0200 Subject: [PATCH 25/32] Update write-json-to-file.md --- snippets/write-json-to-file.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/snippets/write-json-to-file.md b/snippets/write-json-to-file.md index 5cff72064..17de5a44e 100644 --- a/snippets/write-json-to-file.md +++ b/snippets/write-json-to-file.md @@ -5,5 +5,5 @@ Use `fs.writeFile()`, template literals and `JSON.stringify()` to write a `json` ```js const fs = require('fs'); const jsonToFile = (obj, filename) => fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2)) -// jsonToFile({test: "is passed"}, 'testJsonFile') +// jsonToFile({test: "is passed"}, 'testJsonFile') -> writes the object to 'testJsonFile.json' ``` From bb131cf6ebe27ad8fccc33ed1e1631dcefb202f1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stefan=20Feje=C5=A1?= Date: Fri, 15 Dec 2017 12:29:05 +0100 Subject: [PATCH 26/32] Fix capitalize to use more modern ES6 approach --- snippets/capitalize-first-letter.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/snippets/capitalize-first-letter.md b/snippets/capitalize-first-letter.md index 61f73b6a7..edbb04b02 100644 --- a/snippets/capitalize-first-letter.md +++ b/snippets/capitalize-first-letter.md @@ -1,10 +1,11 @@ ### Capitalize first letter -Use `slice(0,1)` and `toUpperCase()` to capitalize first letter, `slice(1)` to get the rest of the string. +Use destructuring and `toUpperCase()` to capitalize first letter, `...rest` to get array of characters after first letter and then `Array.join('')` to make it a string again. Omit the `lowerRest` parameter to keep the rest of the string intact, or set it to `true` to convert to lower case. ```js -const capitalize = (str, lowerRest = false) => - str.slice(0, 1).toUpperCase() + (lowerRest ? str.slice(1).toLowerCase() : str.slice(1)); +const capitalize = ([first,...rest], lowerRest = false) => + first.toUpperCase() + (lowerRest ? rest.join('').toLowerCase() : rest.join('')); +// capitalize('myName') -> 'MyName' // capitalize('myName', true) -> 'Myname' ``` From 4315f06a02a4da70bc8ae5f1c147fa7de161db17 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Fri, 15 Dec 2017 13:33:46 +0200 Subject: [PATCH 27/32] Update shallow clone, tag, build --- README.md | 20 ++++++++++++++++++-- snippets/shallow-clone-object.md | 4 ++-- tag_database | 1 + 3 files changed, 21 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 416266397..ace0e4e80 100644 --- a/README.md +++ b/README.md @@ -83,6 +83,9 @@ ### Media * [Speech synthesis (experimental)](#speech-synthesis-experimental) +### Node +* [Write json to file](#write-json-to-file) + ### Object * [Object from key value pairs](#object-from-key-value-pairs) * [Object to key value pairs](#object-to-key-value-pairs) @@ -943,6 +946,19 @@ const speak = message => { // speak('Hello, World') -> plays the message ``` +[⬆ back to top](#table-of-contents) +## Node + +### Write a JSON to a file + +Use `fs.writeFile()`, template literals and `JSON.stringify()` to write a `json` object to a `.json` file. + +```js +const fs = require('fs'); +const jsonToFile = (obj, filename) => fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2)) +// jsonToFile({test: "is passed"}, 'testJsonFile') -> writes the object to 'testJsonFile.json' +``` + [⬆ back to top](#table-of-contents) ## Object @@ -970,10 +986,10 @@ const objectToPairs = obj => Object.keys(obj).map(k => [k, obj[k]]); ### Shallow clone object -Use the object `...spread` operator to spread the properties of the target object into the clone. +Use `Object.assign()` and an empty object (`{}`) to create a shallo clone of the original. ```js -const shallowClone = obj => ({ ...obj }); +const shallowClone = obj => Object.assign({}, obj); /* const a = { x: true, y: 1 }; const b = shallowClone(a); diff --git a/snippets/shallow-clone-object.md b/snippets/shallow-clone-object.md index c6873c0d8..f3536999f 100644 --- a/snippets/shallow-clone-object.md +++ b/snippets/shallow-clone-object.md @@ -1,9 +1,9 @@ ### Shallow clone object -Use the object `...spread` operator to spread the properties of the target object into the clone. +Use `Object.assign()` and an empty object (`{}`) to create a shallo clone of the original. ```js -const shallowClone = obj => ({ ...obj }); +const shallowClone = obj => Object.assign({}, obj); /* const a = { x: true, y: 1 }; const b = shallowClone(a); diff --git a/tag_database b/tag_database index 67bdedd3c..1a454936f 100644 --- a/tag_database +++ b/tag_database @@ -90,3 +90,4 @@ UUID-generator:utility validate-email:utility validate-number:utility value-or-default:utility +write-json-to-file:node From 3eea464901280837da9d02b7e0d82c79a00e64eb Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Fri, 15 Dec 2017 13:42:31 +0200 Subject: [PATCH 28/32] Build --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index ace0e4e80..4e1b89453 100644 --- a/README.md +++ b/README.md @@ -1031,12 +1031,13 @@ const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperC ### Capitalize first letter -Use `slice(0,1)` and `toUpperCase()` to capitalize first letter, `slice(1)` to get the rest of the string. +Use destructuring and `toUpperCase()` to capitalize first letter, `...rest` to get array of characters after first letter and then `Array.join('')` to make it a string again. Omit the `lowerRest` parameter to keep the rest of the string intact, or set it to `true` to convert to lower case. ```js -const capitalize = (str, lowerRest = false) => - str.slice(0, 1).toUpperCase() + (lowerRest ? str.slice(1).toLowerCase() : str.slice(1)); +const capitalize = ([first,...rest], lowerRest = false) => + first.toUpperCase() + (lowerRest ? rest.join('').toLowerCase() : rest.join('')); +// capitalize('myName') -> 'MyName' // capitalize('myName', true) -> 'Myname' ``` From fb5a958115329c7cc1a1e52e9043c0869e3cddfb Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Fri, 15 Dec 2017 13:50:09 +0200 Subject: [PATCH 29/32] Update remove.md --- snippets/remove.md | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/snippets/remove.md b/snippets/remove.md index 0a25e6f00..f9cfbc8a1 100644 --- a/snippets/remove.md +++ b/snippets/remove.md @@ -1,14 +1,13 @@ ### Remove -Remove elements from `arr` that are returns truthy. Use `Array.filter()` to finding the matching elements and `Array.reduce()` to remove elements using `Array.splice()`.The `func` is invoked with three arguments: (value, index, array). +Use `Array.filter()` to find array elements that return truthy values and `Array.reduce()` to remove elements using `Array.splice()`. +The `func` is invoked with three arguments (`value, index, array`). ```js const remove = (arr, func) => - Array.isArray(arr) ? - arr.filter(func).reduce((acc, val) => { - arr.splice(arr.indexOf(val), 1) - return acc.concat(val); + Array.isArray(arr) ? arr.filter(func).reduce((acc, val) => { + arr.splice(arr.indexOf(val), 1); return acc.concat(val); }, []) - : []; + : []; //remove([1, 2, 3, 4], n => n % 2 == 0) -> [2, 4] ``` From 613eabec3df0f8e4e757425bd113246f622adebb Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Fri, 15 Dec 2017 13:50:46 +0200 Subject: [PATCH 30/32] Update and rename remove.md to array-remove.md --- snippets/{remove.md => array-remove.md} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename snippets/{remove.md => array-remove.md} (96%) diff --git a/snippets/remove.md b/snippets/array-remove.md similarity index 96% rename from snippets/remove.md rename to snippets/array-remove.md index f9cfbc8a1..e08a4a02f 100644 --- a/snippets/remove.md +++ b/snippets/array-remove.md @@ -1,4 +1,4 @@ -### Remove +### Array remove Use `Array.filter()` to find array elements that return truthy values and `Array.reduce()` to remove elements using `Array.splice()`. The `func` is invoked with three arguments (`value, index, array`). From d84a0dad6c21b37a03640be3169e55aa20c08d27 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Fri, 15 Dec 2017 13:51:06 +0200 Subject: [PATCH 31/32] Update array-concatenation.md --- snippets/array-concatenation.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/snippets/array-concatenation.md b/snippets/array-concatenation.md index f441a0a17..40bf43c29 100644 --- a/snippets/array-concatenation.md +++ b/snippets/array-concatenation.md @@ -1,6 +1,6 @@ ### Array concatenation -Use `Array.concat()` to concatenate and array with any additional arrays and/or values, specified in `args`. +Use `Array.concat()` to concatenate an array with any additional arrays and/or values, specified in `args`. ```js const ArrayConcat = (arr, ...args) => [].concat(arr, ...args); From f6b546c40ed1f10b22a2803709cf54d9efa4aea8 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Fri, 15 Dec 2017 13:53:12 +0200 Subject: [PATCH 32/32] Tag and build --- README.md | 21 +++++++++++++++++++-- tag_database | 1 + 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 4e1b89453..e6ada6c41 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,7 @@ * [Array difference](#array-difference) * [Array includes](#array-includes) * [Array intersection](#array-intersection) +* [Array remove](#array-remove) * [Array sample](#array-sample) * [Array union](#array-union) * [Array without](#array-without) @@ -129,8 +130,8 @@ Use `Array.concat()` to concatenate an array with any additional arrays and/or values, specified in `args`. ```js -const arrayConcat = (arr, ...args) => arr.concat(...args); -// arrayConcat([1], 2, [3], [[4]]) -> [1,2,3,[4]] +const ArrayConcat = (arr, ...args) => [].concat(arr, ...args); +// ArrayConcat([1], [1, 2, 3, [4]]) -> [1, 2, 3, [4]] ``` [⬆ back to top](#table-of-contents) @@ -170,6 +171,22 @@ const intersection = (a, b) => { const s = new Set(b); return a.filter(x => s.ha [⬆ back to top](#table-of-contents) +### Array remove + +Use `Array.filter()` to find array elements that return truthy values and `Array.reduce()` to remove elements using `Array.splice()`. +The `func` is invoked with three arguments (`value, index, array`). + +```js +const remove = (arr, func) => + Array.isArray(arr) ? arr.filter(func).reduce((acc, val) => { + arr.splice(arr.indexOf(val), 1); return acc.concat(val); + }, []) + : []; +//remove([1, 2, 3, 4], n => n % 2 == 0) -> [2, 4] +``` + +[⬆ back to top](#table-of-contents) + ### Array sample Use `Math.random()` to generate a random number, multiply it with `length` and round it of to the nearest whole number using `Math.floor()`. diff --git a/tag_database b/tag_database index 1a454936f..20b8fe94a 100644 --- a/tag_database +++ b/tag_database @@ -3,6 +3,7 @@ array-concatenation:array array-difference:array array-includes:array array-intersection:array +array-remove:array array-sample:array array-union:array array-without:array