125
87

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

JavaScript: [๐Ÿˆ, ๐Ÿ•, ๐Ÿ•, ๐Ÿˆ, ๐Ÿˆ, ๐Ÿ•]ใฎใ‚ˆใ†ใช้…ๅˆ—ใ‚’[[๐Ÿˆ, ๐Ÿˆ, ๐Ÿˆ ], [๐Ÿ•, ๐Ÿ•, ๐Ÿ•]]ใซไป•ๅˆ†ใ‘ใ™ใ‚‹

Last updated at Posted at 2020-06-22

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

125
87
9

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
125
87

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?