skip to Main Content

I can’t show to the browser the sum of the elements of an array inside of an object.

Here is my JavaScript code:

const products = {
    productName: [],
    description: [],
    quantity: [],
    unitOfMeasure: []
}
let countLog = products.quantity;`


function sumArray(sum) {

    let displaySumEl = document.getElementById('display-sum');
    sum = countLog.reduce((total, item) => total + item);
    displaySumEl.textContent = `Total: `;
    displaySumEl.textContent += `${parseInt(sum)}`;



    console.log(countLog);

}

Problem in here is that sum variable only shows the numbers in an array not the sum of the numbers in countLog varibale.

2

Answers


  1. function sumArray(sum) {
    let displaySumEl = document.getElementById('display-sum');
     sum = countLog.reduce((total, item) => total + item, 0);
    displaySumEl.textContent = `Total: ${sum}`;
    console.log(countLog);}
    

    the reduce function takes up a second parameter as the initial value of the total

    Login or Signup to reply.
  2. The code provided is trying to sum the elements of the products.quantity array using the reduce() method, but it seems there are no values in the quantity array. If you have an empty array, the reduce() function will throw an error.

    To fix the issue, ensure you have values in the quantity array before calling the reduce() function. If the array might be empty, provide an initial value for the reduce() function to avoid errors.

    Here’s a modified version of your sumArray function:

    function sumArray() {
        let displaySumEl = document.getElementById('display-sum');
        let sum = countLog.reduce((total, item) => total + item, 0); // Added initial value 0
        displaySumEl.textContent = `Total: ${sum}`;
    
        console.log(countLog);
    }
    

    In this modified function, reduce() starts with an initial value of 0. If countLog is an empty array, reduce() will return this initial value, and no error will be thrown.

    Remember to call sumArray() function after you’ve populated the products.quantity array with numbers.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search