I am new to JavaScript and in need of assistance with a particular challenge. How can I extract the "numbers" only from an array containing object values, sum them up, and display the total?
Below is the code related to this query; everything that follows details my progress and what has been achieved so far:
Initially, I start with an empty array:
let customInvoiceItm = []
A function is then used to generate HTML as well as to render items from input fields on the DOM:
// RENDER HTML FROM BOTH INPUTS DESCRIPTION AND COST AND DISPALY VIA invoiceItemsArea.innerHTML
function addCustomItem(renderItems) {
let customItem = ""
for(let i = 0; i < customInvoiceItm.length; i++){
customItem += `
<div class="invoice-task-total">
<h3 id="inv-task" class="item">${renderItems[i].service}</h3>
<a href="" id="remove-btn">remove</a>
<h3 id="inv-total" class="item">$ ${renderItems[i].cost}</h3>
</div>
`
}
// Outputs the input from the input forms onto the screen
invoiceItemsArea.innerHTML = customItem
}
The above function is activated by a button click event, where data from input fields is organized into an Object before being inserted into the array, representing an invoice item/service along with its cost:
// listens for button click and pushes a value from the user entered values from input fields "invoiceDescr" and "invoiceNmbr" Custom Invoice Item Description and Cost into the invoiceArr array
addNewItemBtn.addEventListener("click", function() {
if(invoiceDescr.value === "" && invoiceNmbr.value === "") return
// Object that sorts input values into its own category
let items =
{
service:invoiceDescr.value,
cost:invoiceNmbr.value
}
customInvoiceItm.push(items)
// Clears the Custom Invoice Item and Cost value fields
console.log(customInvoiceItm)
invoiceDescr.value = ""
invoiceNmbr.value = ""
// Saves these values into Browser's local storage
localStorage.setItem("customInvoiceItm", JSON.stringify(customInvoiceItm))
addCustomItem(customInvoiceItm)
})
MY MAIN CONCERN ARISES HERE. I'm attempting to retrieve only the numerical values from the array, calculate their sum, and show it in the Total Amount field within the DOM. This task involves referencing the original array declared at the beginning and using dot notation to access the cost values in all numeric object values within this array like so:
let arrayItems = customInvoiceItm.cost
let sum = arrayItems.reduce((x,y) => x+y)
console.log(sum)
totalAmount.innerText = sum
This approach doesn't yield the desired outcome. Instead, I encounter the following error:
Uncaught TypeError: can't access property "reduce", arrayItems is undefined