大家好,想請問JQuery Arrey怎麼依相同年份加總數值,然後塞到一個新的array裡
還請教各位大大不令指導 謝謝~
array = [
{year: "2018", value: 25063.0894},
{year: "2018", value: 47077.1383},
{year: "2019", value: 326830.9408},
{year: "2019", value: 152327.853},
{year: "2020", value: 312816.5222},
{year: "2020", value: 25552.5231}
]
new_array = [
{year: "2018", sum_value=72,140.2277},
{year: "2019", sum_value=479,158.7938},
{year: "2020", sum_value=338,369.0453}
]
const array = [
{year: "2018", value: 25063.0894},
{year: "2018", value: 47077.1383},
{year: "2019", value: 326830.9408},
{year: "2019", value: 152327.853},
{year: "2020", value: 312816.5222},
{year: "2020", value: 25552.5231}
];
const years = new Set(array.map((item)=> item.year))
var sumByYear = Array.from(years).map((y) => {
return {
'year':y,
'sum_value': array.filter((item)=> item.year == y).reduce((pv, cv)=> pv + cv.value, 0)
}
})
let array = [
{year: "2018", value: 25063.0894},
{year: "2018", value: 47077.1383},
{year: "2019", value: 326830.9408},
{year: "2019", value: 152327.853},
{year: "2020", value: 312816.5222},
{year: "2020", value: 25552.5231}
]
let mapping = {};
array.forEach((item, index, arr) => {
let current_year_string = item.year.toString();
if (!(current_year_string in mapping)) {
mapping[current_year_string] = 0.0;
}
mapping[current_year_string] += item.value;
});
let new_array = [];
for (year in mapping) {
let new_item = {
year: year,
sum_value: mapping[year]
};
new_array.push(new_item);
}