Guide on extracting only numerical data from an array of objects for the purpose of calculating total amounts. Unveiling the challenge of building an

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

Answer №1

To find the total sum of all cost values stored in an array called customInvoiceItm is the main goal.

The code attempted by OP is as follows:

let arrayItems = customInvoiceItm.cost
let sum = arrayItems.reduce((x,y) => x+y)

console.log(sum)
totalAmount.innerText = sum

The issues identified in this code include:

  • The variable customInvoiceItm represents an Array of objects
  • Hence, using customInvoiceItm.cost may not be appropriate
  • As a result, arrayItems might not receive the intended value
  • This leads to an error:
    Uncaught TypeError: can't access property "reduce", arrayItems is undefined
  • The error states that "reduce" cannot be accessed in arrayItems

How to address and resolve these issues:

  • Since customInvoiceItm is an array of objects (and based on additional code snippets, it appears each object has a cost property), there's no need for arrayItems
  • We should iterate through customInvoiceItm and access the cost property of each object
  • Then, we sum up these cost values
  • Considering feedback indicating that cost is treated as a string instead of a number, adding a + before cost resolves this

The updated solution to calculate the total sum:

let sum = customInvoiceItm.reduce(
  (x, {cost}) => x+ +cost,
  0
);

Explanation of why this solution works:

  • The .reduce() method iterates over the customInvoiceItm array
  • In the arrow function parameters (within reduce), we have x as the accumulator and the current object from the array
  • By using {cost}, we destructure the current object to directly access its cost property
  • The implicit return in the arrow function calculates x + +cost for each iteration
  • +cost converts the string value of cost into a number
  • The initial value for x (the aggregator) is set to 0 with , 0

An alternative solution without arrow functions:

let sum = customInvoiceItm
  .reduce(
    function(x, {cost}){
      return (x+ +cost);
    },
    0
  );

The above approach should yield the same result as the previous one.

You could also opt not to destructure or use the + prefix, trying something like this instead:

let sum = customInvoiceItm
  .reduce(
    function(x, item){
      return (x + Number(item.cost));
    },
    0
  );

Please note that sharing such basic explanations is typically discouraged, as they are better covered in tutorials and similar resources. This answer may be deleted based on feedback from the community (if any).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Replacing a JSON vault using XHR: A step-by-step guide

Can someone assist me in replacing the JSON data from a JSON file on a website using JavaScript XHR? setagaya.json: {"trains":[{"operation_number":1,"line_id":26007,"station_id":784,"track_number":1,"up":true},{"operation_number":2,"line_id":26007,"stati ...

Encountering an issue with a MEAN application using Angular 2: The error message states "Cannot read property

As a first-time application developer, I am working on creating a system to manage Client profiles. Utilizing the Angular tour of heroes for the basic structure, I integrated mongodb and express components sourced from various online platforms. However, I ...

Ways to incorporate encoded HTML text into string literals

When attempting to insert a HTML encoded special character within a string literal, I am encountering an issue where it does not display as intended in the final document. The approach I am taking is as follows: const head = { title: `${ApplicationName} ...

Transfer a concealed input value to javascript using the href attribute

I have a question about using javascript to handle the href attribute. Here is the code snippet I am working with: <script> window.onunload = refreshParent; function refreshParent() { var SAPno = document.getElementById('Hidden ...

Enclosing Material UI's DataGrid GridActionsCellItem within a custom wrapper component triggers a visual glitch if showInMenu is enabled

Here is how my MUI DataGrid columns are structured: const columns = [ { field: "name", type: "string" }, { field: "actions", type: "actions", width: 80, getActions: (params) => [ ...

Struggling to align the Title Tags perfectly in the center of Images

When attempting to center align images and their post titles, I encountered an issue where the left part of the image and title were being cut off by a small margin. Despite trying various methods, I was unable to successfully center the title tags. You ca ...

Is it possible to incorporate dynamic variables into the directives of a nested loop? Plus, thoughts on how to properly declare variables in a node.js environment

Question Explanation (Zamka): <----------------------------------------------------------------------------------------------------------> Input Example: 100 500 12 1st Line: represents the left bound (L) 2nd Line: represents the right bound ...

Which data types in JavaScript have a built-in toString() method?

Positives: 'world'.toString() // "world" const example = {} example.toString() // "[object Object]" Negatives: true.toString() // throws TypeError false.toString() // throws TypeError Do you know of any other data types that wi ...

Once the timer has finished, I would like for a specific component to be displayed

I am trying to make my component CountDownSquare disappear once the timer has fully counted down. In my homePageData, I have the main text stored in a h3 element that should only appear once the countdown is complete. I attempted to use a ternary stateme ...

"Enhancing event handling: Using addEventListener natively with selectors similar to .on()

Has anyone figured out how to replicate jQuery's .on() method in vanilla JavaScript? The native addEventListener function doesn't seem to have the capability to filter based on child/selector elements, and delving into event bubbling and capturin ...

Introducing the innovative Icon Collapsable JQuery - a versatile tool that

I'm looking to set custom icons for the JQuery Collapsable view without having to make changes to the default JQuery CSS and .JS files. You can take a look at my starting point on jsFiddle here: http://jsfiddle.net/jakechasan/M7LLU/ Although I' ...

What is the best way to obtain the inner ID with JQuery?

How can I assign values to inside id using JQuery? Sample code from controller.cs: public GroupModel Get() { IGroupTypeRepository groupTypeRepo = new GroupTypeRepository(); IGroupRepository groupRepo = new GroupRepository(); var model = new ...

Is it advisable to use npm devDependencies in a production environment?

While reviewing the package.json file for one of our products at work, I noticed that the SDK uses socket.io for a crucial function even though socket.io-client is listed as a devDependency. Despite this discrepancy, the SDK works flawlessly for our clie ...

What is the best way to retrieve the value of a property within a JavaScript object?

I am facing an issue with retrieving the value of the status property from an object in my code. Below is a snippet of what I have tried: console.log("Resource.query()"); console.log(Resource.query()); console.log("Resource.query().status"); console.log(R ...

How do you create an AngularJS directive with HTML content?

I am currently working on a directive that aims to load a webpage, make it accessible in a service, and also have its content available in the scope within the directive's element. Here is a simplified explanation of what I am trying to achieve: < ...

Unable to create canvas drawings using fingertips on mobile web browsers

Check out the code snippet below: canvas = document.getElementById("canvas"); ctx = canvas.getContext('2d'); tmp_ctx = element[0].getContext('2d'); element.bind('mousemove touchmove', function(event){ if(draw ...

Techniques for simulating functions in Jest

I have a pair of basic components that I'm currently creating tests for using jest. My goal is to verify that when I click on a currencyItem, the corresponding array gets added to the select state. To achieve this, I am passing the handleCurrencyToggl ...

When clicking on HTML input fields, they do not receive focus

I am facing a puzzling issue where I am unable to access the input fields and textareas on my HTML form. The JS, HTML, and CSS files are too large for me to share here. Could someone provide guidance on what steps to take when troubleshooting this unusual ...

Obtain the AJAX response in separate div elements depending on whether it is successful or an error

Currently, my jQuery script outputs the result in the same div for error or success messages: HTML <div id="error-message").html(res); JQUERY jQuery('#register-me').on('click',function(){ $("#myform").hide(); jQuery ...

Managing post requests within the express.js framework

I need assistance utilizing the value provided in a form within Node.js. Here is an example: index.html : <!DOCTYPE html> <html lang="en"> <head> </head> <body> <div align="middle" > <!--Ethernet ...