From 7f532a074d6fb774ece27aca12afff4c9a9326ab Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Fri, 26 Jan 2018 13:48:50 +0200 Subject: [PATCH] Add pullBy --- snippets/pullBy.md | 25 +++++++++++++++++++++++++ tag_database | 3 ++- 2 files changed, 27 insertions(+), 1 deletion(-) create mode 100644 snippets/pullBy.md diff --git a/snippets/pullBy.md b/snippets/pullBy.md new file mode 100644 index 000000000..b8d523a39 --- /dev/null +++ b/snippets/pullBy.md @@ -0,0 +1,25 @@ +### pullBy + +Mutates the original array to filter out the values specified, based on a given iterator function. + +Check if the last argument provided in a function. +Use `Array.map()` to apply the iterator function `fn` to all array elements. +Use `Array.filter()` and `Array.includes()` to pull out the values that are not needed. +Use `Array.length = 0` to mutate the passed in an array by resetting it's length to zero and `Array.push()` to re-populate it with only the pulled values. + +```js +const pullBy = (arr, ...args) => { + const length = args.length; + let fn = length > 1 ? args[length - 1] : undefined; + fn = typeof fn == 'function' ? (args.pop(), fn) : undefined; + let argState = (Array.isArray(args[0]) ? args[0] : args).map(val => fn(val)); + let pulled = arr.filter((v, i) => !argState.includes(fn(v))); + arr.length = 0; + pulled.forEach(v => arr.push(v)); +}; +``` + +```js +var myArray = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }]; +pullBy(myArray, [{ 'x': 1 }, { 'x': 3 }], o => o.x); // myArray = [{ x: 2 }] +``` diff --git a/tag_database b/tag_database index 2ddb8058d..34456499e 100644 --- a/tag_database +++ b/tag_database @@ -177,6 +177,7 @@ promisify:adapter,function,promise pull:array pullAtIndex:array pullAtValue:array +pullBy:array,function,advanced randomHexColorCode:utility,random randomIntArrayInRange:math,utility,random randomIntegerInRange:math,utility,random @@ -256,4 +257,4 @@ xProd:array,math yesNo:utility,regexp zip:array zipObject:array,object -zipWith:array,advanced +zipWith:array,function,advanced