I have an array topArr that I am attempting to get the sum of the results object. I using the .reduce() method in order to accomplish this. I am then declaring another variable to equal the sum with comma placements.
I have two attempt code snippet examples below.
First, I am getting a return value of [object Object]48,883.
Second example, I am getting a return value of the first number in the array, it is not combining the other object.
I am expecting the result of both results combined to equal the amount 543,810
Here are my code snippets.
let topArr = [
{ result: "494,927", risk: "HIGH", sector: "Online" },
{ result: "48,883", risk: "HIGH", sector: "Retail Stores" },
],
sum = topArr.reduce(function (a, e) {
return a + Number(e.result.replace(/(,\s*)+/g, '').trim());
})
let sumComma = sum.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
console.log(sumComma)
let topArr = [
{ result: "494,927", risk: "HIGH", sector: "Online" },
{ result: "48,883", risk: "HIGH", sector: "Retail Stores" },
],
sum = topArr.reduce(function (e) {
return Number(e.result.replace(/(,\s*)+/g, '').trim());
})
let sumComma = sum.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
console.log(sumComma)