@jswork/filter2tuple
v1.0.4
Published
A function to split an array into two tuples based on a filtering condition.
Downloads
4
Readme
filter2tuple
A function to split an array into two tuples based on a filtering condition.
installation
npm install @jswork/filter2tuple
usage
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:
// 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.