How do I get Total sum of a column in Vue JS
You can add a row manually and each row is in "items" array
items: [
{
occuGroup:'',
constType:'',
bfloorArea: 0,
cfloorArea: 0
},
],
Here's the code that I wrote to get Total
subTotal: function() {
var total = 0;
this.items.forEach(element => {
total += (element.bfloorArea);
});
return total;
},
How do I get that right? Thanks
#1 Answers
It seems to be you are concat string. You will need to convert string to int for your summation.
this.items.forEach(element => {
total += parseInt(element.bfloorArea);
});
#2 Answers
I would combine map and reduce array functions:
subtotal() {
return this.items
.map(({bfloorArea}) => bfloorArea)
.reduce((a, b) => a + b, 0)
}
Using map this way you get a new array containing only the values of bfloorArea, and with reduce you get the total sum of those values.
Hope that helps!
Note: If you need the total of any other property you can just change "bfloorArea" for the property you want. If the property is not in Number type but a string, you can cast it to number when mapping:
.map(({propertyToCast}) => Number(propertyToCast))
#3 Answers
The problem with your code is you are adding items as a string instead, you need number type.
subTotal: function() {
return this.items.reduce((acc, ele) => {
return acc + parseInt(ele.bfloorArea);
}, 0);
},
function subTotal(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(subTotal(items));
#4 Answers
Another solution without using object destructing could be
return this.items.map(item => item.bfloorArea)
.reduce((prev, current) => prev + parseInt(current,10), 0);
#5 Answers
Use correct input type
I want to give a different option. Many suggested to convert the string from the input field, since the default type of an input is string.
You didn't include template data so I am just assuming you are in fact using a standard input field like (or something similar)
<input v-bind="item.bFloorArea" />
In Vue you already have the inbuilt option to automatically typecast the input as a Number, therefore your initial code could have worked if you used something like
<input v-bind.number="item.bFloorArea" type="number" />
Please note the modifier .number for Value Binding ( From the docs : https://vuejs.org/v2/guide/forms.html#number )
❗ This would also disallow for the user to input text into a field which clearly needs a number

Comments
Post a Comment