Jquery key is the same, value is added, and finally sorted according to the key value, ask for advice?

var arr = [{
                "32": 297
            },
            {
                "32": 3944
            },
            {
                "322": 297
            },
            {
                "322": 297
            },
            {
                "312": 3944
            },
            {
                "312": 297
            },
            {
                "132": 3944
            },
            {
                "32": 3944
            },
            {
                "34": 458
            }
        ]

expectation: same key, value sum, last sort

Jul.07,2021

var obj = {}
arr.forEach(item => {
  Object.keys(item).forEach(key => {
    if (obj[key]) {
      obj[key] += item[key]
    } else {
      obj[key] = item[key]
    }
  })
})
var ret = Object.keys(obj).sort((a, b) => obj[a] - obj[b]).map(key => ({
  [key]: obj[key]
}))
console.log(ret)

skillfully write a

let arr1 = Object.entries(arr.reduce((res, val) => (key = Object.keys(val)[0], {...res, [key]: val[key] + res[key] || 0}), {})).sort((a, b) => a[1] - b[1]).map(val => ({[val[0]]: val[1]}))
console.log(arr1)

Brothers, use foreach to let a variable and then + = value is not fine. As for sorting, push each value to a new array and then sort it by sort

.
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1e5053b-450c0.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1e5053b-450c0.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?