"Error: Unable to calculate the sum because s.sum is not recognized as a valid function. This occurred while trying to sum the property values of

I have a JavaScript object with JSON data

var info = [  
   {  
      "MONTH":"  2018-01",
      "DEPARTMENT":"Legals",
      "EMPLOYEE":"Smith A.",
      "AMOUNT":"14289.66"
   },
   {  
      "MONTH":"  2018-01",
      "DEPARTMENT":"Legals",
      "EMPLOYEE":"Jonson B.",
      "AMOUNT":"7408.05"
   },
   {  
      "MONTH":"  2018-01",
      "DEPARTMENT":"Legals",
      "EMPLOYEE":"Lee C.",
      "AMOUNT":"10102.98"
   }
]

I am trying to calculate the total sum of the 'AMOUNT' property using the following function (taken from this source):

info.sum = function(data, property){
    return data.reduce( function(prev, current){
        return prev + parseFloat(current[property]);
    }, 0);
};

totalAmount = info.sum(info, 'AMOUNT');

However, I encounter an error message: "TypeError: info.sum is not a function"

How can I correctly calculate the sum of 'AMOUNT' values within the object?

Answer №1

Check out this code snippet:

var data = [  
   {  
      "MONTH":"  2018-01",
      "DEPARTMENT":"Legals",
      "EMPLOYEE":"Smith A.",
      "AMOUNT":"14289.66"
   },
   {  
      "MONTH":"  2018-01",
      "DEPARTMENT":"Legals",
      "EMPLOYEE":"Jonson B.",
      "AMOUNT":"7408.05"
   },
   {  
      "MONTH":"  2018-01",
      "DEPARTMENT":"Legals",
      "EMPLOYEE":"Lee C.",
      "AMOUNT":"10102.98"
   }
];
data.__proto__.sum = function(items, prop){
    return items.reduce( function(a, b){
        return a + +b[prop];
    }, 0);
};

totalAmount = data.sum(data, 'AMOUNT');
console.log(totalAmount);

I added a sum function to the prototype and included type conversion in the return statement. This code has been tested and works correctly on Firefox, Chrome, and Edge browsers.

Answer №2

My intention is not to provide you with the exact steps on how to execute this task, but rather to respond to your inquiry in a manner that closely aligns with what you have presented. To achieve this, you can simply extract the string stored in the AMOUNT property and convert it into a floating point number.

s.calculateSum = function(arr) {
  return arr.reduce(function(acc, obj) {
    return acc += parseFloat(obj.AMOUNT);
  }, 0);
}

If you wish to see a live demonstration, feel free to explore this codepen link.

Answer №3

Initially, I encountered an error message due to my s variable being of string type. Therefore, I needed to convert it into an array.

The use of the AND function with proto - proved effective for me.

s.__proto__.sum = function(items, prop){
    return items.reduce( function(a, b){
        return a + +b[prop];
    }, 0);
};

sTotal = s.sum(s, 'AMOUNT');
console.log(sTotal);

A sincere thank you to everyone involved!

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

What is the best way to exclude empty fields from an API response when using the .map() function in Nextjs

I've created a custom repository API that I want to integrate into my Next.js web application. However, if any field in the API is empty, I need to exclude that particular element. The contents of my API: { "myrepo": [ { ...

Leverage the power of ExpressJS by seamlessly sharing route middleware between routes

Looking for a way to share multiple route middleware across various routes and controllers? Check out this setup: In app.js, we require ./routes/index.js: // load fs module var fs = require('fs'); // import routing files module.exports = func ...

Remove a property from an object using Object.assign()

Is there a way to remove a key using Object.assign() rather than setting the value to undefined in this scenario? In my code, I am utilizing .filter() to iterate through certain items. When a match is found, I aim to modify the x-property value while also ...

"Enhanced interactivity: Hover effects and selection states on an image map

Hello there, I need assistance with my code. Here it is: <img id="body_image" usemap="#body_map" src="assets/images/body.jpg" alt=""> <map name="body_map"> <area shape="poly" alt="d" href="#body_chart" name="ad" coords="153, 153, 145, 1 ...

In need of a collection of modules determined by a DefinePlugin constant

Currently, I am in the process of constructing a web application utilizing Webpack. However, I have encountered a challenge with a particular aspect of the design - hopefully someone in this forum has experience in similar tasks (or possesses enough knowle ...

What steps can be taken to troubleshoot and resolve this specific TypeScript compilation error, as well as similar errors that may

I am struggling with this TypeScript code that contains comments and seems a bit messy: function getPlacesToStopExchange(): { our: { i: number; val: number; }[]; enemy: { i: number; val: number; }[]; //[party in 'our' | 'enemy' ]: ...

Revamping the vertices and UVs of DecalGeometry

I am currently experimenting with ThreeJS decals. I have successfully added a stunning decal to my sphere. Below is the code snippet I am using to place the decal on my sphere. (Please disregard any custom classes mentioned in the code.) // Creating the ...

What is the process for incorporating transparency into the .dae model?

let importedMesh; loader.load("test_obj/dae/07.DAE", function (result) { importedMesh = result.scene.children[0].children[0].clone(); importedMesh.scale.set(1, 1, 1); importedMesh.position.set(0, 0, 0); importedMesh.opaci ...

No response received when sending AJAX request from PHP to Node.js

Recently, I encountered a situation where I needed to send data from my php page to my node.js server and receive a response from it. Below is the ajax code snippet that I used to send the data from my php page, which was running on an Apache server: fun ...

Is there a way to cancel hiding on a q-dialog?

I'm currently working on integrating a confirmation modal within a dialog box that includes form input fields. The purpose is to alert the user when they try to exit without saving their changes. The modal should appear every time the user modifies th ...

What is the process for adjusting the form transition?

I am currently working on a form that has a transition effect However, I encountered an issue: check out the problem here My goal is to keep the magnifying glass fixed in place while the form moves Here is a snippet of my code: import Search fro ...

Is it possible for you to simulate the shift key being pressed prior to the event execution?

Is there a way to allow the user to scroll left and right horizontally without having to hold the shift key down? I want to achieve this effect by setting the "shiftKey" variable to true even when it is not physically pressed. Any suggestions on how to ...

Converting Cyrillic characters to ASCII codes using JavaScript: A step-by-step guide

Is there a reliable method to convert characters from the CP1251 table to ASCII codes ranging from 0 to 255? So far, I have only come across the charCodeAt() function which is limited to codes up to 128. It returns a Unicode number for codes above that r ...

Step-by-step guide on transforming jQuery code into Vue JS:

Recently delving into Vue, attempting to translate previous JS + JQuery code into Vue Here is the list I'm working with: <ul id="progressbar"> <li class="active">integration Ip's</li> <li>T ...

Ways to retrieve information from a request handler

Working with express, node, and handlebars, I've implemented this piece of code to manage POST requests. When a user hits the "add item" button, it captures their input for a city, fetches the weather data for that city using the Open Weather Map API, ...

Using properties to generate a header component in TypeScript

I am currently exploring TypeScript and incorporating it into a project for the first time. I'm encountering a challenge as I am not sure what to call this concept, making it difficult to search for solutions. If someone can provide me with the term, ...

The function $scope.$watch(var,function) was not defined and caused an error stating that

Having trouble with the error message: "undefined is not a function" popping up when attempting to add a watch to the scope. I've been staring at this code for so long now, but still unable to locate the source of the issue. Why am I getting an undef ...

The content of xmlhttp.responseText is not being displayed in the innerHTML

As part of my ongoing effort to enhance my understanding of Ajax for work purposes, I have been following the W3Schools tutorial and experimenting with my Apache2 server. In this process, I have placed a file named ajax_info.txt on the server (in /var/www ...

Angular JS not displaying texts properly

Within my code, I have implemented a feature to display an h4 element stating that there are no products found if the search query does not match any strings. However, I am encountering a strange bug where the text fails to appear as intended. Interestingl ...

Script for tracking user activity on Facebook and Google platforms

I currently have Google tracking conversion set up, but now I also need to implement Facebook pixel tracking. My existing Google Head Script code is as follows: <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||fu ...