LoginSignup
3
1

More than 3 years have passed since last update.

JavaScript の Array に zip 関数を生やしてみる

Posted at

TL;DR

Array.prototype.zip = function(...args) {
  const new_array = [];
  for(let i = 0; i < this.length; i ++) {
    new_array.push([this[i], ...args.map(arg => arg[i])]);
  }
  return new_array;
}

詳細

やっていることは単純で同じインデックスの値同士の組み合わせを作って新しい配列に push しているだけですね。もともとは Ruby の Array#zip のようなことを JavaScript でもできないかなと思って探していたんですが、どうやらネイティブでは実装されていないようなので今回作ってみた次第です。

実際に使ってみるとこんな感じになります。

const array0 = [0, 1, 2];
const array1 = [3, 4, 5];
const array2 = [6, 7, 8];

array0.zip(array1, array2) // => [[ 0, 3, 6 ], [ 1, 4, 7 ], [ 2, 5, 8 ]]

参考文献

3
1
4

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