LoginSignup
69
42

More than 5 years have passed since last update.

JavaScript で flatten

Last updated at Posted at 2012-08-23

配列の配列を展開します。

var nested = [
  [0, 1, 2],
  [3, 4, 5],
  [6, 7, 8]
];
Array.prototype.concat.apply([], nested);
// -> [0, 1, 2, 3, 4, 5, 6, 7, 8]

apply が配列を引数として展開してくれるおかげで、以下と同じようなことになるためです。

[].concat(nested[0], nested[1], nested[2]);
// -> [0, 1, 2, 3, 4, 5, 6, 7, 8]

Concatenating an array of arrays in Coffeescript - Stack Overflow で知りました。これは便利。

Array を拡張するならこんな感じですね。

Array.prototype.flatten = function() {
  return Array.prototype.concat.apply([], this);
};
69
42
5

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
69
42