2

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)

2 Answers 2

5

You aren't passing an initial value to the .reduce, so the initial value defaults to the first item in the array, which is an object - so a + Number(...) results in concatenating the object (coerced to a string) with the Number call.

Pass an initial value of 0 instead:

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());
  }, 0)

let sumComma = sum.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");

console.log(sumComma)

Sign up to request clarification or add additional context in comments.

Comments

0

You need to give reduce an initial value to add up from

const sum = topArr.reduce((acc, cur) => {
     return acc + Number(cur.result.replace(/(,\s*)+/g, '').trim());
}, 0)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.