diff --git a/snippets/array-pull-(mutates-array).md b/snippets/array-pull-(mutates-array).md new file mode 100644 index 000000000..3a58225ca --- /dev/null +++ b/snippets/array-pull-(mutates-array).md @@ -0,0 +1,14 @@ +### Array pull (mutates array) + +Use `Array.filter()` and `Array.includes()` to pull out the values that are not needed. +Use `Array.length = 0` to mutate the passed in array by resetting it's length to zero and `Array.push()` to re-populate it with only the pulled values. + +```js +const pull = (arr, ...args) => { + let pulled = arr.filter((v, i) => args.includes(v)); + arr.length = 0; pulled.forEach(v => arr.push(v)); +}; +// let myArray = ['a', 'b', 'c', 'a', 'b', 'c']; +// pull(myArray, 'a', 'c'); +// console.log(myArray) -> [ 'b', 'b' ] +``` diff --git a/tag_database b/tag_database index 6cce617ea..07e07435a 100644 --- a/tag_database +++ b/tag_database @@ -56,7 +56,7 @@ is-function:utility is-number:utility is-string:utility is-symbol:utility -JSON-to-date:date +json-to-date: last-of-list:array log-function-name:function measure-time-taken-by-function:utility @@ -71,6 +71,7 @@ pick:array pipe-functions:function powerset:math promisify:function +pull:array random-integer-in-range:math random-number-in-range:math read-file-as-array-of-lines:node @@ -98,4 +99,4 @@ URL-parameters:utility UUID-generator:utility validate-email:utility validate-number:utility -write-JSON-to-file:node +write-json-to-file: