@jswork/filter2tuple
TypeScript icon, indicating that this package has built-in type declarations

1.0.4 • Public • Published

filter2tuple

A function to split an array into two tuples based on a filtering condition.

version license size download

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.

Readme

Keywords

Package Sidebar

Install

npm i @jswork/filter2tuple

Homepage

js.work

Weekly Downloads

0

Version

1.0.4

License

MIT

Unpacked Size

6.15 kB

Total Files

6

Last publish

Collaborators

  • afeiship