linche0859
9/20/2019 - 12:32 PM

資料分類主副檔

      let data = [
        {
          id: '20190919',
          name: 'A',
          amount: 100
        },
        {
          id: '20190919',
          name: 'B',
          amount: 200
        },
        {
          id: '20190920',
          name: 'A',
          amount: 100
        },
        {
          id: '20190920',
          name: 'C',
          amount: 300
        },
        {
          id: '20190918',
          name: 'B',
          amount: 200
        },
        {
          id: '20190918',
          name: 'C',
          amount: 300
        }
      ]

      function show() {
        let sort = []

        data.forEach(item => {
          let obj = {}

          let noAdd = sort.every(({ id }) => id !== item.id)

          if (noAdd) {
            obj.id = item.id
            obj.detail = data.filter(({ id }) => item.id === id)
            obj.total = obj.detail.reduce((prev, curr) => prev + curr.amount, 0)
            sort.push(obj)
          }
        })
        return sort
      }