What is the best way to calculate the total sum of a column in Vue JS?

https://i.sstatic.net/K8Rqj.png

To manually add a row, each row is stored in the "items" array

items: [
  {
    occuGroup:'',
    constType:'',
    bfloorArea: 0,
    cfloorArea: 0
  },
],

Below is the code I wrote to calculate the total:

subTotal: function() {
  var total = 0;
  this.items.forEach(element => {
    total += (element.bfloorArea);
  });
  return total;
},

Any suggestions on how I can improve this? Thanks!

Answer №1

One effective approach would be to utilize the map and reduce array functions:

calculateTotal() {
  return this.items
    .map(({areaSize}) => areaSize)
    .reduce((accumulator, currentValue) => accumulator + currentValue, 0)
}

By using the map function in this manner, a new array is generated that only contains the values of areaSize. The reduce function then calculates the total sum of those values.

I trust this explanation proves helpful!

Additional Note: Should you require the total of any other property, simply substitute "areaSize" with the desired property. In cases where the property is not of type Number but rather a string, you can convert it to a number while mapping:

.map(({propertyToConvert}) => Number(propertyToConvert))

Answer №2

Your code has a mistake where you are treating items as strings instead of numbers, which is causing the issue.

subTotal: function() {
  return this.items.reduce((acc, ele) => {
    return acc + parseInt(ele.bfloorArea);
  }, 0);
},

function calculateSubTotal(items) {
  return items.reduce((acc, ele) => {
    return acc + parseInt(ele.bfloorArea);
  }, 0);
}

const items = [
  {
    occuGroup: "",
    constType: "",
    bfloorArea: 0,
    cfloorArea: 0,
  },
  {
    occuGroup: "",
    constType: "",
    bfloorArea: 4,
    cfloorArea: 0,
  },
  {
    occuGroup: "",
    constType: "",
    bfloorArea: 6,
    cfloorArea: 0,
  }
];

console.log(calculateSubTotal(items));

Answer №3

Looks like you're combining strings. Make sure to convert them to integers before adding them up.

this.items.forEach(item => {
    sum += parseInt(item.size);
  });

Answer №4

Here's an alternative method that doesn't involve object destructuring:

Consider trying this approach instead:
return this.items.map(item => item.bfloorArea)
    .reduce((prev, current) => prev + parseInt(current,10), 0);

Answer №5

Using the Correct Input Type

I have a different approach to suggest. Many people recommend converting the string from the input field, as the default type of an input is usually a string.

Assuming you are using a standard input field or something similar and not providing template data, your initial code could have worked if you utilized Vue's ability to automatically cast the input as a Number. For this purpose, consider using:

<input v-bind.number="item.bFloorArea" type="number" />

Remember to add the modifier .number for Value Binding. More details can be found in the documentation: https://v2.vuejs.org/v2/guide/forms.html#number


This method will prevent users from entering text into a field where only numbers should be accepted

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 purpose of using a hash in a WebSocket handshake?

When establishing a Websocket connection, the client initiates by connecting to a tcp socket on a server and then performs a handshake. In the client's handshake, there is a base64 encoded key (Sec-WebScoket-Key). The expected response from the serv ...

Why does starting up the Firebase emulators trigger the execution of one of my functions as well?

Upon running firebase emulators:start --only functions,firestore, the output I receive is as follows: $ firebase emulators:start --only functions,firestore i emulators: Starting emulators: functions, firestore ⚠ functions: The following emulators are ...

PHP + MySQL + JavaScript for an Interactive Web Communication Platform

My goal is to develop a Web Chat system using PHP, MySQL, and JavaScript. Currently, I store messages in a MySQL database with an incremental ID (indexed), timestamp, sender, and message. To retrieve new messages, I use AJAX to query the database every 50 ...

Angular JS is throwing an error because it cannot recognize the property 'push' of undefined

Would like to automatically update the div using $scope.push encountering an issue: Error: Cannot read property 'push' of undefined Here are my JSON and JavaScript snippets: JSON {"records":[{"total":"156000"}]} JavaScript $scope.plusCar ...

Saving numerous files with Promises

There is a Node URL (created using Express) that enables users to download static images of addresses. The calling application sends a request to the /download URL with multiple addresses in JSON format. The download service then calls Google Maps to save ...

Refresh a different Angular Controller after submitting a POST request

Just to clarify, I am looking to dynamically reload another controller with new data after a POST request without refreshing the page. Here is my code: No issues with saving data to the database. Script var app = angular.module('userBase', []) ...

Efficiently handling jsonwebtoken errors in node and express

Here is the verification function I've created: exports.verifyToken = function(req, res, next){ var token = req.body.token; jwt.verify(token, config.sessionSecret, function(err, decoded) { if(err){ return next(err); }else{ ...

Integrate an external script with React and initialize a new instance

I've been working on integrating a neat canvas background feature from this GitHub project into my React web application. Here's what I've attempted: import {WarpSpeed} from './warpspeed.js' import WarpSpeed from './warpspee ...

What is the proper method for securing this?

Trying to retrieve 'this' within a method that is invoked by pressing a button, where this points to both the class and the pressed button: p.myVar = 'apple'; $('.go').on('click', this._init); p._init = function(e ...

I am facing difficulties displaying the egin{cases}…end{cases} equation using Jekyll's MathJax

MathJax is used on our course website. We have implemented MathJax in Jekyll and hosted it on GitHub pages. While MathJax works well for simple equations, I have faced difficulties with more complex ones. Despite spending hours investigating and experiment ...

Experiencing unexpected outcomes via AJAX requests

Linked to: Query Database with Javascript and PHP This inquiry is connected to my previous question. I made adjustments to the PHP script based on one of the responses I received; however, when attempting to utilize $.getJSON, I encountered difficulties. ...

Deleting an item using jQuery

In the Document Object Model (DOM), there is a button available to remove the parent element here: <i class="fa fa-times remove-product-compare" aria-hidden="true"></i> Here is an example of my DOM structure: <div class="col-lg-12 col-md- ...

What steps should I take to show the content on different menu selections?

Check out my full code snippet. <html> <head> <meta charset="utf-8"> <title>Title</title> <link rel="stylesheet" href="https://code.jquery.com/mobile/1.5.0-rc1/jquery.mobile ...

What is the best way to limit the range slider before it reaches its maximum point?

I am currently utilizing angularjs to stop a range slider at 75%, however, the method I am using is not very efficient and is not working as desired. Is there anyone who can provide guidance on how to achieve this? Please note: I want to display a total ...

Avoid TypeError: cannot read property '0' of undefined in a Vue.js/Django project

I am currently working on a Django/Vue.js application. Upon submitting the login form, the Django view redirects to the user's username page, where the Vue.Js file retrieves data from the server. Below is the code snippet: async created(){ await ...

Struggling to toggle the visibility of a table with a button - successfully hiding it, but unable to make it reappear?

I need a button that can toggle (show/hide) a table. Currently, my code hides the table successfully, but it fails to show the table again when I click the button. It seems like there is an issue with refreshing or redirecting after clicking the button for ...

Looking for someone to break down this Typescript code snippet for me

As a Javascript developer, I am currently diving into an unfamiliar TypeScript code block within a project. Here is the code snippet: ViewModel newPropertyAddress = new ViewModel(){name, previousPro = oldValue } ...

Create a CSS popup alert that appears when a button is clicked, rather than using

Is there a way to customize CSS so that the popup alert focuses on a button instead of just appearing like this? https://i.sstatic.net/r25fd.jpg I have implemented this type of validation for a text box: <div class="form-group"> <label class="co ...

How can I interpret a string with a specific format using JavaScript?

Input String: var json_data = "{0:'apple', 1:'bannana', 2:'guava'}"; Desired Output after parsing with JavaScript: var json_data = { columns: [{0:'apple'}, {1:'bannana'} ,{2:'guava'}] ...

Calculate the overall length of a specified time interval using Node Js

My task involves calculating overtime based on work start and end times. We are looking to calculate overtime hours that fall outside of the regular work schedule. For example, the regular work timings are from 10:00 AM to 07:00 PM Overtime needs to be ...