5
3

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 5 years have passed since last update.

JavaScript:配列をzipWith/zipする関数

Last updated at Posted at 2018-03-28

そういえばなかったなと思い、自分でも必要になったので作ってみました。

  • 2引数関数fと配列xsとysを引数に
  • 要素数の少ない方に合わせて
  • xs,ysの要素にfを適用して配列にする
const zipWith = f => xs => ys => 
  (xs.length < ys.length)? xs.map( (e, i) => f( e, ys[i] ) ) 
  : ys.map( (e, i) => f( xs[i], e) )

zipは配列xs、ysの同インデックスの要素からなる配列の配列を返します。

const zip = zipWith( (x, y) => [x, y] )
//あるいは
const zip = xs => ys => 
  (xs.length < ys.length) ? xs.map( (e, i) =>[e,  ys[i]] ) 
  : ys.map((e, i) => [xs[i], e] );
5
3
0

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
5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?