linqのgroupByのような処理をjavascriptで使う

groupByは抽象化されたブレーク処理だと考えることができるので、使い所は多い。

// groupByの定義
Array.prototype.groupBy = function(convertKeyFunc) {
	let groupList = [];
	let group = null;
	
	let first = true;
	for (const item of this) {
		const currentKey = convertKeyFunc(item);
		if (first) {
			first = false;
			group = { key: currentKey, items: [] };
		} else if (currentKey != group.key) {
			groupList.push(group);
			group = { key: currentKey, items: [] };
		}
		group.items.push(item);
	}
	if (group !== null) { groupList.push(group); }

	return groupList;
}

// 使用例
[ "a-10", "a-20", "a-30", "b-10", "c-10", "c-20" ].groupBy(i => i.substr(0, 1)).forEach(group => {
	console.log(`-- start: ${group.key} --`);
	for (const item of group.items) {
		console.log(item);
	}
	console.log(`-- end  : ${group.key} --`);
});

// 出力
// -- start: a --
// a-10
// a-20
// a-30
// -- end  : a --
// -- start: b --
// b-10
// -- end  : b --
// -- start: c --
// c-10
// c-20
// -- end  : c --