简体   繁体   中英

Perform a aggregate function inside a reduce function

Basically, I want to divide the sumOfSquareOfLoadings and itemCount in the same reduce function, where I am summing them and getting the count. But I am stuck in implementation because I have to perform the division to the aggregated value.

It seems I need to perform the division in another array? or is there any way I can perform the division in the same reduce function where I am aggregating other values?

 var newArray1 = [{ ltd: "Cpt", stdSquare: "0.35", error: "0.65" }, { ltd: "Cpt", stdSquare: "0.16", error: "0.84" }, { ltd: "Ant", stdSquare: "0.21", error: "0.79" }, { ltd: "Ant", stdSquare: "0.79", error: "0.21" } ]; var counts = newArray1.reduce((r, { ltd }) => (r[ltd] = (r[ltd] || 0) + 1, r), {}); var newArray = []; const result = [...newArray1.reduce((r, o) => { const key = o.ltd; const item = r.get(key) || Object.assign({}, o, { sumOfSquareOfLoadings: 0, itemCount: counts[key], sumOferrors: 0, ave: 0 }); item.sumOfSquareOfLoadings += parseFloat(o.stdSquare); item.sumOferrors += parseFloat(o.error); item.ave = item.sumOfSquareOfLoadings / item.itemCount; return r.set(key, item); }, new Map).values()]; console.log(result);

I want to divide the value of item.sumOfSquareOfLoadings and the item.itemCount and store the result in ave .

Expected Output:

[
  {
    "ltd": "Cpt",
    "error": "0.65",
    "sumOfSquareOfLoadings": 0.51,
    "itemCount": 2,
    "sumOferrors": 1.49,
    "ave": 0.25  /* sumOfSquareOfLoadings / itemCount */
  },
  {
    "ltd": "Ant",
    "error": "0.79",
    "sumOfSquareOfLoadings": 1,
    "itemCount": 2,
    "sumOferrors": 1,
    "ave": 0.5   /* sumOfSquareOfLoadings / itemCount */
  }
]

Instead of make an isolated array just for counting occurence, you could directly count that an accumulate the item count right in each reduce's iteratation

const item =
  r.get(key) ||
  Object.assign({}, o, {
    sumOfSquareOfLoadings: 0,
    itemCount: 0,
    sumOferrors: 0,
    ave: 0,
  })

item.itemCount += 1

Full demo

 var newArray1 = [ { ltd: "Cpt", stdSquare: "0.35", error: "0.65", }, { ltd: "Cpt", stdSquare: "0.16", error: "0.84", }, { ltd: "Ant", stdSquare: "0.21", error: "0.79", }, { ltd: "Ant", stdSquare: "0.79", error: "0.21", }, ] var newArray = [] const result = [ ...newArray1 .reduce((r, o) => { const key = o.ltd const item = r.get(key) || Object.assign({}, o, { sumOfSquareOfLoadings: 0, itemCount: 0, sumOferrors: 0, ave: 0, }) item.itemCount += 1 item.sumOfSquareOfLoadings += parseFloat(o.stdSquare) item.sumOferrors += parseFloat(o.error) item.ave = item.sumOfSquareOfLoadings / item.itemCount return r.set(key, item) }, new Map()) .values(), ] console.log(result)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM