Also pass index into predicate

master
Sven Slootweg 5 years ago
parent dd1e088dd5
commit 78a78b44cb

@ -30,7 +30,9 @@ console.log(odd); // [ 1, 3, 5, 7 ]
Splits the `array` into a truthy and a falsy side, based on what the `predicate` function returns. Note that like `Array#map`, whether a value 'matches' depends on whether the returned value is [__truthy__](https://developer.mozilla.org/en-US/docs/Glossary/Truthy), not just a literal `true`.
- __array:__ The array to split.
- __predicate:__ The function that determines which side to sort the value into.
- __predicate:__ The function that determines which side to sort the value into. This predicate function receives two arguments, of which you'll usually only need the first one:
- __value:__ The value itself.
- __index:__ The index of the value in the array you've provided.
Returns an array with two elements:
@ -38,3 +40,13 @@ Returns an array with two elements:
- __1:__ The elements that __did not match__ the predicate function (ie. returned a falsy value).
It's strongly recommended to use [array destructuring](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Array_destructuring) in handling the returned array (like in the example), as this will greatly improve readability of your code.
## Changelog
# 1.1.0 (August 19, 2019)
- __New:__ Predicate function now also receives the index of the value as an argument, not just the value itself.
# 1.0.0 (August 19, 2019)
Initial release.

@ -4,8 +4,8 @@ module.exports = function splitFilter(array, predicate) {
let truthy = [];
let falsy = [];
for (let item of array) {
if (predicate(item)) {
for (let [ i, item ] of array.entries()) {
if (predicate(item, i)) {
truthy.push(item);
} else {
falsy.push(item);

Loading…
Cancel
Save