Help us understand the problem. What is going on with this article?

JavaScript: [🐈, 🐕, 🐕, 🐈, 🐈, 🐕]のような配列を[[🐈, 🐈, 🐈 ], [🐕, 🐕, 🐕]]に仕分けする

JavaScriptの配列を要素の内容に応じて、2つのグループに仕分け(partitioning)する方法です。

下の例では、要素が犬か猫かによって仕分けしています:

partition.js
const pets = ['🐈', '🐕', '🐕', '🐈', '🐈', '🐕']

const [cats, dogs] = pets.reduce(
  ([cats, dogs], pet) =>
    pet === '🐈' ? [[...cats, pet], dogs] : [cats, [...dogs, pet]],
  [[], []]
)

console.log(cats, dogs)
//=> [ '🐈', '🐈', '🐈' ] [ '🐕', '🐕', '🐕' ]

ちなみにTypeScriptではreduceの型引数に[string[], string[]]を指定します:

partition.ts
const pets = ['🐈', '🐕', '🐕', '🐈', '🐈', '🐕']

const [cats, dogs] = pets.reduce<[string[], string[]]>(
  ([cats, dogs], pet) =>
    pet === '🐈' ? [[...cats, pet], dogs] : [cats, [...dogs, pet]],
  [[], []]
)

console.log(cats, dogs)

仕訳処理を汎用化すると:

partition.js
const partition = (array, predicate) =>
  array.reduce(
    ([left, right], value) =>
      predicate(value) ? [[...left, value], right] : [left, [...right, value]],
    [[], []]
  )
const pets = ['🐈', '🐕', '🐕', '🐈', '🐈', '🐕']
const [cats, dogs] = partition(pets, value => value === '🐈')
partition.ts
const partition = <
  T extends ReadonlyArray<any>,
  U extends T[number],
  V extends Exclude<T[number], U>
>(
  array: T,
  predicate: (value: T[number]) => value is U
): [U[], V[]] =>
  array.reduce(
    ([left, right], value) =>
      predicate(value) ? [[...left, value], right] : [left, [...right, value]],
    [[], []]
  )

const pets = ['🐈', '🐕', '🐕', '🐈', '🐈', '🐕'] as const
const [cats, dogs]: ['🐈'[], '🐕'[]] = partition(pets, (value): value is '🐈' => value === '🐈')

最後までお読みくださりありがとうございました。Twitterでは、Qiitaに書かない技術ネタなどもツイートしているので、よかったらフォローしてもらえると嬉しいです:relieved:→Twitter@suin

suin
Qiita 4位/TypeScript入門書執筆中/TypeScripterのための座談会「YYTypeScript」主催/『実践ドメイン駆動設計』書籍邦訳レビュア/分報Slack考案/YYPHP主催/CodeIQマガジン執筆/株式会社クラフトマンソフトウェア創設/Web自動テスト「ShouldBee」の開発/TypeScript/DDD/OOP
https://yyts.connpass.com/
shouldbee
開発者向けテスト支援サービスShouldBeeを開発・運営するスタートアップ(onlab第8期)
http://shouldbee.at
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした