Removes elements from an array for which the given function returns false.
Use Array.prototype.filter() to find array elements that return truthy values and Array.prototype.reduce() to remove elements using Array.prototype.splice(). The func is invoked with three arguments (value, index, array).
const remove = (arr, func) => Array.isArray(arr) ? arr.filter(func).reduce((acc, val) => { - arr.splice(arr.indexOf(val), 1); - return acc.concat(val); - }, []) + arr.splice(arr.indexOf(val), 1); + return acc.concat(val); + }, []) : [];
remove([1, 2, 3, 4], n => n % 2 === 0); // [2, 4]
Returns a random element from an array.
Use Math.random() to generate a random number, multiply it by length and round it off to the nearest whole number using Math.floor(). This method also works with strings.
const sample = arr => arr[Math.floor(Math.random() * arr.length)]; diff --git a/snippets/remove.md b/snippets/remove.md index 58de9c2e0..a8c472774 100644 --- a/snippets/remove.md +++ b/snippets/remove.md @@ -9,9 +9,9 @@ The `func` is invoked with three arguments (`value, index, array`). const remove = (arr, func) => Array.isArray(arr) ? arr.filter(func).reduce((acc, val) => { - arr.splice(arr.indexOf(val), 1); - return acc.concat(val); - }, []) + arr.splice(arr.indexOf(val), 1); + return acc.concat(val); + }, []) : []; ``` diff --git a/test/_30s.js b/test/_30s.js index cadfa3f13..a7576a756 100644 --- a/test/_30s.js +++ b/test/_30s.js @@ -963,9 +963,9 @@ const reject = (pred, array) => array.filter((...args) => !pred(...args)); const remove = (arr, func) => Array.isArray(arr) ? arr.filter(func).reduce((acc, val) => { - arr.splice(arr.indexOf(val), 1); - return acc.concat(val); - }, []) + arr.splice(arr.indexOf(val), 1); + return acc.concat(val); + }, []) : []; const removeNonASCII = str => str.replace(/[^\x20-\x7E]/g, ''); const renameKeys = (keysMap, obj) => diff --git a/test/testlog b/test/testlog index 3768d5f6c..7958cd036 100644 --- a/test/testlog +++ b/test/testlog @@ -2321,7 +2321,7 @@ ok 1234 — defer is a Function # Test Suites: 100% ██████████, 360 passed, 360 total # Tests: 100% ██████████, 1234 passed, 1234 total -# Time: 53.433s +# Time: 52.713s # Ran all test suites.