數組對象的總數比方說,我在JavaScript中有如下數據結構:的Javascript計算百分比由關鍵
const data = [
{year: 2017, kind: "mammal", animal: "dog", total: 5},
{year: 2017, kind: "mammal", animal: "dog", total: 3},
{year: 2016, kind: "mammal", animal: "dog", total: 5},
{year: 2016, kind: "bird", animal: "chicken", total: 5},
{year: 2016, kind: "bird", animal: "chicken", total: 90}
];
我希望能夠指定一個鍵或多個鍵,例如year
到組數據通過。所以,如果我指定year
作爲組由我會想計算總計如下:
[{year: 2017, kind: "mammal", animal: "dog", count: 8, pct: 1},
{year: 2016, kind: "mammal", animal: "dog", count: 5, pct: 0.05},
{year: 2016, kind: "bird", animal: "chicken", count: 95, pct: 0.95}]
或者,如果我通過year
和kind
指定組總計我希望以下內容:
[{year: 2017, kind: "mammal", animal: "dog", count: 8, pct: 1},
{year: 2016, kind: "mammal", animal: "dog", count: 5, pct: 1},
{year: 2016, kind: "bird", animal: "chicken", count: 95, pct: 1}]
如何我可以在Javascript中實現這個嗎?我已經看過使用d3的嵌套函數,但迄今爲止還沒有成功將我的頭部包裹在實現中。
你試過什麼了? – Luca
看看'sort'和'reduce'方法。 [數組文檔](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) – Will