1
0
Fork 0
Library that lets you filter an array and keep both pieces
Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.
 
Sven Slootweg aafc7308f3 1.1.3 vor 4 Jahren
README.md Fix repository URL in package.json vor 4 Jahren
example.js Initial commit vor 5 Jahren
index.js Also pass index into predicate vor 5 Jahren
package.json 1.1.3 vor 4 Jahren

README.md

split-filter

Like Array#filter, but you get to keep both pieces. Quite literally. Splits the array by a predicate function.

If you want to split an array into more than two arrays, you'll want to use split-filter-n instead.

Example

"use strict";

const splitFilter = require("split-filter");

function isEven(number) {
	return Math.abs(number) % 2 === 0;
}

let numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8];

let [ even, odd ] = splitFilter(numbers, (number) => isEven(number));

console.log(even); // [ 0, 2, 4, 6, 8 ]
console.log(odd); // [ 1, 3, 5, 7 ]

API

splitFilter(array, predicate)

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, not just a literal true.

  • array: The array to split.
  • 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:

  • 0: The elements that matched the predicate function (ie. for which the predicate function returned a truthy value).
  • 1: The elements that did not match the predicate function (ie. returned a falsy value).

It's strongly recommended to use array destructuring in handling the returned array (like in the example), as this will greatly improve readability of your code.

Changelog

1.1.3 (February 17, 2020)

  • Fixed repository URL in package.json

1.1.2 (August 26, 2019)

  • Fixed changelog formatting

1.1.1 (August 26, 2019)

  • Fixed incorrect require in documentation example.

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.