JavaScriptで「_id」キーの値が同じオブジェクトをグループ化して集計する方法
まず、次のようなオブジェクトの配列があると仮定します。
const arr = [
{_id : "1", S : "2"},
{_id : "1", M : "4"},
{_id : "2", M : "1"},
{_id : "6" , M : "1"},
{_id : "3", S : "3"}
];この配列を受け取り、「_id」キーの値が同じオブジェクト同士をひとつのグループにまとめ、さらに各キーの数値を合計したTotal付きの結果を返すJavaScript関数を作成する必要があります。
最終的な出力は次のようになります。
const output = [
{_id : "1", M : "4", S : "2", Total: "6"},
{_id : "2", M : "1", S : "0", Total: "1"},
{_id : "6", M : "1", S : "0", Total: "1"},
{_id : "3", M : "0", S : "3", Total: "3"}
];実装例
この処理を実現するコードは次のとおりです。
const arr = [
{_id : "1", S : "2"},
{_id : "1", M : "4"},
{_id : "2", M : "1"},
{_id : "6" , M : "1"},
{_id : "3", S : "3"}
];
const pickAllConstraints = arr => {
let constraints = [];
arr.forEach(el => {
const keys = Object.keys(el);
constraints = [...constraints, ...keys];
});
return constraints.filter((el, ind) => el !== '_id' && ind === constraints.lastIndexOf(el));
};
const buildItem = (cons, el = {}, prev = {}) => {
const item = {};
let total = 0
cons.forEach(i => {
item[i] = (+el[i] || 0) + (+prev[i] || 0);
total += item[i];
});
item.total = total;
return item;
}
const buildCumulativeArray = arr => {
const constraints = pickAllConstraints(arr);
const map = {}, res = [];
arr.forEach(el => {
const { _id } = el;
if(map.hasOwnProperty(_id)){
res[map[_id] - 1] = {
_id, ...buildItem(constraints, el, res[map[_id] - 1])
};
}else{
map[_id] = res.push({
_id, ...buildItem(constraints, el)
});
}
});
return res;
};
console.log(buildCumulativeArray(arr));コードの解説
- pickAllConstraints(): 配列内のすべてのオブジェクトから「_id」以外のキー名(集計対象となる項目)を重複なく抽出します。
- buildItem(): 各グループに対して、これまでの累積値に新しいオブジェクトの値を加算し、その合計(total)も併せて計算します。値が存在しない場合は
|| 0によって0として扱われるため、欠損キーがあっても安全に集計できます。 - buildCumulativeArray(): オブジェクト(マップ)を使って同じ「_id」が出現済みかどうかを追跡し、初登場なら新規エントリとして追加、既存なら該当エントリの値を累積更新していきます。
出力
コンソールには次のように表示されます。
[
{ _id: '1', M: 4, S: 2, total: 6 },
{ _id: '2', M: 1, S: 0, total: 1 },
{ _id: '6', M: 1, S: 0, total: 1 },
{ _id: '3', M: 0, S: 3, total: 3 }
]
-
JavaScriptで値に基づいてオブジェクトをグループ化する方法
JavaScriptでは、reduce()メソッドを活用することで、配列内のオブジェクトを特定の値(プロパティ)に基づいて効率的にグループ化できます。たとえば、複数人のデータを「年齢」ごとにまとめたい場合などに役立ちます。ここでは、実際に動作するサンプルコードをもとに、実装手順と仕組みをわかりやすく解説します。 サンプルコード <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewpo
-
JavaScriptでオブジェクトにreduceメソッドを適用する方法
JavaScriptのreduce()メソッドは本来配列向けのメソッドのため、オブジェクトにそのまま適用することはできません。そこで、Object.values()メソッドを使ってオブジェクトの値を配列として取り出し、その配列に対してreduce()を適用します。 以下は、JavaScriptでオブジェクトの値にreduceメソッドを適用するコード例です。 コード例 <!DOCTYPE html> <html lang=en> <head> <meta charset=UTF-8 /> <meta name=viewport content