https://github.com/afeiship/filter2tuple
A function to split an array into two tuples based on a filtering condition.
https://github.com/afeiship/filter2tuple
array filter split tuple
Last synced: 4 months ago
JSON representation
A function to split an array into two tuples based on a filtering condition.
- Host: GitHub
- URL: https://github.com/afeiship/filter2tuple
- Owner: afeiship
- License: mit
- Created: 2023-09-07T01:48:38.000Z (over 2 years ago)
- Default Branch: main
- Last Pushed: 2023-09-07T02:22:40.000Z (over 2 years ago)
- Last Synced: 2025-02-07T12:31:58.044Z (about 1 year ago)
- Topics: array, filter, split, tuple
- Language: TypeScript
- Homepage:
- Size: 12.7 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE.txt
Awesome Lists containing this project
README
# filter2tuple
> A function to split an array into two tuples based on a filtering condition.
[![version][version-image]][version-url]
[![license][license-image]][license-url]
[![size][size-image]][size-url]
[![download][download-image]][download-url]
## installation
```shell
npm install @jswork/filter2tuple
```
## usage
```js
import filter2tuple from '@jswork/filter2tuple';
const numbers = [1, 2, 3, 4, 5, 6];
const [even, odd] = filter2tuple(numbers, (item) => item % 2 === 0);
console.log(even, odd);
// [2, 4, 6] [1, 3, 5]
```
## other
> Use reduce implement:
```js
// impl1:
function filter2tuple(arr, filterFn) {
return arr.reduce((result, item) => {
filterFn(item) ? result[0].push(item) : result[1].push(item);
return result;
}, [[], []]);
}
// impl2:
function filter2tuple(arr, filterFn) {
return arr.reduce(
(result, item) => {
const idx = Number(!filterFn(item));
result[idx].push(item);
return result;
},
[[], []]
);
}
```
## license
Code released under [the MIT license](https://github.com/afeiship/filter2tuple/blob/master/LICENSE.txt).
[version-image]: https://img.shields.io/npm/v/@jswork/filter2tuple
[version-url]: https://npmjs.org/package/@jswork/filter2tuple
[license-image]: https://img.shields.io/npm/l/@jswork/filter2tuple
[license-url]: https://github.com/afeiship/filter2tuple/blob/master/LICENSE.txt
[size-image]: https://img.shields.io/bundlephobia/minzip/@jswork/filter2tuple
[size-url]: https://github.com/afeiship/filter2tuple/blob/master/dist/index.min.js
[download-image]: https://img.shields.io/npm/dm/@jswork/filter2tuple
[download-url]: https://www.npmjs.com/package/@jswork/filter2tuple