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
the reduce function takes up a second parameter as the initial value of the total
The code provided is trying to sum the elements of the
products.quantity
array using thereduce()
method, but it seems there are no values in the quantity array. If you have an empty array, thereduce()
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 thereduce()
function to avoid errors.Here’s a modified version of your
sumArray
function:In this modified function,
reduce()
starts with an initial value of 0. IfcountLog
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 theproducts.quantity
array with numbers.