首頁 > web前端 > js教程 > 主體

如何透過多個屬性有效地將數組中的物件分組和聚合?

Linda Hamilton
發布: 2024-11-14 16:06:02
原創
522 人瀏覽過

How can I efficiently group and aggregate objects in an array by multiple properties?

Efficiently Grouping and Aggregating objects in an Array by Multiple Properties

In this article, we address a critical task: Grouping objects within an array by multiple properties and aggregating their values.

The Challenge

Grouping objects in arrays based on multiple criteria can be a perplexing problem. While existing solutions can group objects by multiple keys, they often fail to effectively combine and eliminate duplicates. Our goal is to create a solution that seamlessly groups objects by shape and color, sums their respective 'used' and 'instances' values, and eliminates duplicates.

The Solution

Our approach utilizes the array.reduce() method in conjunction with a helper object. For each object in the array, we construct a unique key by concatenating its shape and color. We then check if this key exists in our helper object:

  1. If the key exists, we simply increment the 'used' and 'instances' values of the corresponding object in the helper.
  2. If the key does not exist, we create a new object with a copy of the original and add it to the helper object using Object.assign(). We also push this object into the result array.

By using a helper object to keep track of unique combinations of shape and color, we effectively group and aggregate objects while eliminating duplicates.

var arr = [{"shape":"square","color":"red","used":1,"instances":1},
{"shape":"square","color":"red","used":2,"instances":1},
{"shape":"circle","color":"blue","used":0,"instances":0},
{"shape":"square","color":"blue","used":4,"instances":4},
{"shape":"circle","color":"red","used":1,"instances":1},
{"shape":"circle","color":"red","used":1,"instances":0},
{"shape":"square","color":"blue","used":4,"instances":5},
{"shape":"square","color":"red","used":2,"instances":1}
];

var helper = {};
var result = arr.reduce(function(r, o) {
  var key = o.shape + '-' + o.color;

  if(!helper[key]) {
    helper[key] = Object.assign({}, o); // create a copy of o
    r.push(helper[key]);
  } else {
    helper[key].used += o.used;
    helper[key].instances += o.instances;
  }

  return r;
}, []);

console.log(result);
登入後複製

The Output

By implementing this solution, we obtain the desired result:

[{"shape":"square","color":"red","used":5,"instances":3},
{"shape":"circle","color":"red","used":2,"instances":1},
{"shape":"square","color":"blue","used":11,"instances":9},
{"shape":"circle","color":"blue","used":0,"instances":0}]
登入後複製

This effectively groups objects by shape and color, sums up their values, and removes duplicates.

以上是如何透過多個屬性有效地將數組中的物件分組和聚合?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板