0
0

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】配列をN個で分割(前方開始・後方開始)

Last updated at Posted at 2020-11-20

【JavaScript】自分なりのワンライナー(配列操作)
過去に書いた上記記事で、配列の分割をワンライナーで載せましたが、そうじゃない書き方をしたかったので書きました。

それだけじゃつまらないので後方から分割するものも書いてみました。

**(追記)**ご指摘がありました、第2引数検査を追加しました。

#コード(前方から)


const splitArray = (arr, n = 1) => {
	if (!Number.isFinite(n) || n < 1) return arr;		//追記
	
	const result = new Array();
	for (let i = 0, len = arr.length; i < len; i += n) {
		result.push( arr.slice(i, i + n) );
	}
	//n個未満の配列を除外したい時に追加
	//if (result.slice(-1)[0].length < n) result.pop();
	return result;
};

const array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

console.log ( splitArray(array, 3) );      //[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
console.log ( splitArray(array, 4) );      //[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9]]

#コード(後方から)


const splitArrayBack = (arr, n = 1) => {
	if (!Number.isFinite(n) || n < 1) return arr;		//追記
	
	const result = new Array();
	for (let i = arr.length, len = i + n; i > 0; i -= n) {
		result.unshift( arr.slice(i - len, i) );
	}
	//n個未満の配列を除外したい時に追加
	//if (result[0].length < n) result.shift();
	return result;
};

const array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

console.log ( splitArrayBack(array, 3) );      //[[0], [1, 2, 3], [4, 5, 6], [7, 8, 9]]
console.log ( splitArrayBack(array, 4) );      //[[0, 1], [2, 3, 4, 5], [6, 7, 8, 9]]

0
0
2

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?