iT邦幫忙

0

JQuery Arrey 相同年份數值相加問題

  • 分享至 

  • xImage

大家好,想請問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}
]

小火車 iT邦新手 4 級 ‧ 2022-10-24 09:47:40 檢舉
感謝大大的指教 謝謝!
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中
2
froce
iT邦大師 1 級 ‧ 2022-10-21 15:43:28
最佳解答
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)
      }
})
小火車 iT邦新手 4 級 ‧ 2022-10-24 09:47:44 檢舉

感謝大大的指教 謝謝!

1
天黑
iT邦研究生 5 級 ‧ 2022-10-21 15:23:16

也許你需要的是 Array.reduce()
連結

2
woeichern
iT邦新手 1 級 ‧ 2022-10-22 13:39:00
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);
}
小火車 iT邦新手 4 級 ‧ 2022-10-24 09:47:50 檢舉

感謝大大的指教 謝謝!

我要發表回答

立即登入回答