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

js 配列を二次元配列のグループにわける

More than 3 years have passed since last update.

お題

・配列(第一引数)を指定された数字(第二引数)で二次元配列のグループに分ける。

function chunkArrayInGroups(arr, size) {
//write your code.
}
chunkArrayInGroups(["a", "b", "c", "d"], 2);

出力結果 例

(["a", "b", "c", "d"], 2) // [["a", "b"], ["c", "d"]]
([0, 1, 2, 3, 4, 5], 3)   // [[0, 1, 2], [3, 4, 5]]
([0, 1, 2, 3, 4, 5], 2)   // [[0, 1], [2, 3], [4, 5]]
([0, 1, 2, 3, 4, 5], 4)   // [[0, 1, 2, 3], [4, 5]]

使った関数

push()
slice()

一番最初に試したコード

function chunkArrayInGroups(arr, size) {
  var newArray = [];
  for(var i = 0; i<arr.length; i+=size){
    var j = arr.slice(i,i+size);
    newArray.push(j);
  }
  return newArray;
}
chunkArrayInGroups(["a", "b", "c", "d"], 2);

考え方

・必要なツールを考える
配列の要素を切り出す  → slice()
切り出した要素を配列に格納する → push()
複数回繰り返す → for文 while文

・slice()の引数の取り方を考える
chunkArrayInGroups(["a", "b", "c", "d"], 2);の場合に欲しい引数
一回目(0,2)→ a b が切り出される
二回目(2,4)→ c d が切り出される
この数値をfor文でどのようにとるか考える。
一回目
0→ 変数iの初期値で設定
2→ sizeの値で取れる
二回目
2→ iにsizeを代入すると取得できる
(増減式にsizeの分だけ増えて行くように設定する →i+=size)
4→ 増減式で増えたi(2)に再度size(2)を足すことで取得

最後に、変数jに切り分けた数字を入れて、push()でnewArrayに格納する。

while文のコード

function chunkArrayInGroups(arr, size) {
  var newArr = [];
  var i = 0;
  while (i < arr.length) {
    newArr.push(arr.slice(i, i+size));
    i += size;
  }
  return newArr;
}

他にもコードが浮かんだ方、コメントお待ちしてます。

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
ユーザーは見つかりませんでした