How to calculate array of numbers in vuejs - vue.js

I have array. in that array there is a field name debit. I want to add all the debit on this array and find the total. I am trying to do this with reduce function. but it's adding number as character not calculating the sum of the array number. here is the code
export default {
data() {
return {
fields: {
debit: 0,
credit: 0,
type: '',
},
fields: [],
allDebit: 0,
allCredit: 0,
}
},
methods: {
newfield() {
this.fields.push({
debit: 0,
credit: 0,
type: '',
})
},
dataRemove(index) {
Vue.delete(this.fields, index);
},
calculate() {
this.allDebit = this.fields.reduce((acc, item) => acc + item.debit, 0);
}
}
}
output:
{
"fields": [
{
"debit": "4",
"credit": "2",
"type": ""
},
{
"debit": "4",
"credit": "2",
"type": ""
}
],
"allDebit": "044",
"allCredit": 0
}

fields: {
debit: 0,
credit: 0,
type: '',
},
fields: [],
You specify object fields and array in the data. You cannot have an object with two identical keys in the object literal. That is not a valid JS. I wouldn't be surprised if that was the reason.
Also, your values in output seem to all be strings. Try parseInt function in the reduce function.

convert string to number and then sum them
calculate() {
this.allDebit = this.fields.reduce((acc, item) => Number(acc) + Number(item.debit), 0);
}

Rename first fields to field, or remove it completely, I do not see where do you use it.
Parse to integer item.debit either in the accumulator or in the place where do you set it.
The possible fix:
export default {
data() {
return {
field: {
debit: 0,
credit: 0,
type: '',
},
fields: [],
allDebit: 0,
allCredit: 0,
}
},
methods: {
newfield() {
this.fields.push({
debit: 0,
credit: 0,
type: '',
})
},
dataRemove(index) {
Vue.delete(this.fields, index);
},
calculate() {
this.allDebit = this.fields.reduce((acc, item) => acc + parseInt(item.debit), 0);
}
}
}

export default {
data() {
return {
fields: { // this is identical to the fields: [] array
// you need to rename it to something like field (Singular)
debit: 0,
credit: 0,
type: '',
},
// maybe you ment
field: { // field (Singular)
debit: 0,
credit: 0,
type: '',
},
//
fields: [], // THIS !!!
allDebit: 0,
allCredit: 0,
}
},
methods: {
newfield() {
this.fields.push({
debit: 0,
credit: 0,
type: '',
})
},
calculate() {
const { debit } = this.fields.reduce((acc, item) => {
return { debit: acc.debit + item.debit };
}, { debit: 0 })
this.allDebit = debit;
}
}
}
You can't have 2 identical keys in the data function property.

I would do this in a computed property instead, so that the value is calculated again if fields changes.
computed: {
allDebit() {
return this.fields.reduce((acc, item) => acc + parseInt(item.debit), 0);
}
}
EDIT: You can't have two properties with the same key in your data function. You have fields two times.

Related

Apex Line Area chart is not getting displayed on the page in Vuejs

I am stuck on a page where i am not able to display the charts on the page.
To make it simplify what I have done is, here is the code sandbox:
I see there an error in console about the data, I am not sure about it.
https://codesandbox.io/s/compassionate-snyder-bckoq
I want to display the chart like this (as an example), but I am not able to display on the code sandbox
Please help.
The format of series is not aligned with ApexCharts.
You need to transform the data to match with ApexChart format.
Please see the changes in the codesandbox.
https://codesandbox.io/s/small-dew-eztod?file=/src/components/HelloWorld.vue
options: {
// X axis labels
xaxis: {
type: 'date',
categories: ["2021-05-04", "2021-05-05", "2021-05-07"]
},
},
series: [
{
name: "total",
data: [2, 2, 1],
},
{
name: "pending",
data: [0, 1, 0],
},
{
name: "approved",
data: [2, 1, 1],
},
{
name: "rejected",
data: [0, 0, 0],
},
],
Transform data to fit ApexChart
const data = {
"2021-05-04": {
total: 2,
pending: 0,
approved: 2,
rejected: 0,
},
"2021-05-05": {
total: 2,
pending: 1,
approved: 1,
rejected: 0,
},
"2021-05-07": {
total: 1,
pending: 0,
approved: 1,
rejected: 0,
},
};
const xaxis = {
type: "date",
categories: Object.keys(data).map((key) => key), // ['2021-05-04', '2021-05-05', '2021-05-07']
};
let statusObj = [];
for (const dataValue of Object.values(data)) { // get the values from keys '2021-05-04', '2021-05-05' ...
// loop the values, e.g. 1st loop: { total: 2, pending: 0, approved: 2, rejected: 0, }
for (const [key, value] of Object.entries(dataValue)) {
// take 'total' as example, find if statusObj already has { name: 'total', data: [x] }, e.g. statusObj = { name: 'total', data: [1] }
const existingStatusIndex = Object.keys(statusObj).find(
(sKey) => statusObj[sKey].name === key
);
// if yes, return the index of it
if (existingStatusIndex) {
// add new data value to existing data object. e.g. { name: 'total', data: [1, 2] }
statusObj[existingStatusIndex].data.push(value);
continue;
}
// if no, create a new object and add it to statusObj
statusObj.push({
name: key,
data: [value],
});
}
}
Output:
xaxis {
type: 'date',
categories: [ '2021-05-04', '2021-05-05', '2021-05-07' ]
}
statusObj [
{ name: 'total', data: [ 2, 2, 1 ] },
{ name: 'pending', data: [ 0, 1, 0 ] },
{ name: 'approved', data: [ 2, 1, 1 ] },
{ name: 'rejected', data: [ 0, 0, 0 ] }
]

Fulltext mongodb $text search query in graphql-compose-mongoose

I'm unable to figure out how to construct a graphql query for performing the mongodb fulltext search using the text index. https://docs.mongodb.com/manual/text-search/
I've already created a text index on my string in the mongoose schema but I don't see anything in the schemas that show up in the grapqhl playground.
A bit late, though I was able to implement it like so
const FacilitySchema: Schema = new Schema(
{
name: { type: String, required: true, maxlength: 50, text: true },
short_description: { type: String, required: true, maxlength: 150, text: true },
description: { type: String, maxlength: 1000 },
location: { type: LocationSchema, required: true },
},
{
timestamps: true,
}
);
FacilitySchema.index(
{
name: 'text',
short_description: 'text',
'category.name': 'text',
'location.address': 'text',
'location.city': 'text',
'location.state': 'text',
'location.country': 'text',
},
{
name: 'FacilitiesTextIndex',
default_language: 'english',
weights: {
name: 10,
short_description: 5,
// rest fields get weight equals to 1
},
}
);
After creating your ObjectTypeComposer for the model, add this
const paginationResolver = FacilityTC.getResolver('pagination').addFilterArg({
name: 'search',
type: 'String',
query: (query, value, resolveParams) => {
resolveParams.args.sort = {
score: { $meta: 'textScore' },
};
query.$text = { $search: value, $language: 'en' };
resolveParams.projection.score = { $meta: 'textScore' };
},
});
FacilityTC.setResolver('pagination', paginationResolver);
Then you can assign like so
const schemaComposer = new SchemaComposer();
schemaComposer.Query.addFields({
// ...
facilities: Facility.getResolver('pagination')
// ...
});
On your client side, perform the query like so
{
facilities(filter: { search: "akure" }) {
count
items {
name
}
}
}

Using Custom Sort with Track Scores set to True is still showing score as null

So I'm setting a default query in my React Native app. Essentially I'm trying to set a sortOrder based on the elementOrder values. My partner used this same piece of code in his web app and it works for him. It doesn't seem to work on my end. The score exists if I remove the custom sort, which is normal due to what I've read in the docs. When I'm using a custom sort, then I should add track_scores: true. My score is still coming up as null.
I am not sure how to debug this situation. Can someone point me in the right direction? Thanks! Here's my code and let me know if you need to see anything. Unfortunately I don't have access to Kibana. I'm just console logging the list item and it's properties.
const defaultQueryConfig = {
track_scores: true,
sort: {
_script: {
type: 'number',
script: {
lang: 'painless',
source: `
int sortOrder = 0;
if (doc['elementOrder'].value == 1) {sortOrder = 3}
else if (doc['elementOrder'].value == 3) {sortOrder = 2}
else if (doc['elementOrder'].value == 2) {sortOrder = 1}
sortOrder;
`,
},
order: 'desc',
},
},
query: {
function_score: {
query: {
match_all: {},
},
functions: [
{
filter: {
match: {
categoryType: 'earth',
},
},
weight: 100,
},
{
filter: {
match: {
categoryType: 'water',
},
},
weight: 90,
},
{
filter: {
match: {
categoryType: 'fire',
},
},
weight: 80,
},
{
filter: {
match: {
thingExists: false,
},
},
weight: 2,
},
],
score_mode: 'multiply',
},
},
};

How to declare Vuex gettres return data in a map function

I have declared state and getters in my vuex where I want to get new price and title of the existing products in state.
When I have declared the return data in the getters It is throwing a syntax error and which is ; expected , given.
But from my point of view it is correct so what is the exact error?
state: {
value1: 1,
products: [
{ title: 'Hp1', price: 500 },
{ title: 'Hp2', price: 600 },
{ title: 'Hp3', price: 700 },
]
},
getters: {
saleProducts: state => {
var newProductsList = state.products.map(product => {
return
{
title: '** '+ product.title +' **',
price: product.price/2 + " % Off"
}
});
return newProductsList;
}
}
This is a bit bizzarre. When I copied and pasted your code then it doesn't work. When I type it in by hand myself from your example, then it works. Usually this sort of thing means that you've got an invalid ASCII character in the mix somewhere. The main thing I changed was to using double quotes instead of single quotes:
state: {
value1: 1,
products: [
{ title: 'Hp1', price: 500 },
{ title: 'Hp2', price: 600 },
{ title: 'Hp3', price: 700 },
]
},
getters: {
saleProducts: state => {
var newProductsList = state.products.map(product => {
return {
title: "** " + product.title + " **",
price: product.price/2 + " % Off"
}
})
}
},
See if you can spot the difference. Here's the codesandbox.io link: https://codesandbox.io/s/ywr1v7my19
Browse to /store/modules/main.js to see it in situ.

Mongodb: get count of multiple values in a field grouped by another field

I have a collection as below
{"country":"US","city":"NY"}
{"country":"US","city":"AL"}
{"country":"US","city":"MA"}
{"country":"US","city":"NY"}
{"country":"US","city":"MA"}
{"country":"IN","city":"DL"}
{"country":"IN","city":"KA"}
{"country":"IN","city":"DL"}
{"country":"IN","city":"DL"}
{"country":"IN","city":"KA"}
and expecting an output
{ "data": { "US": {"NY": 2,"AL": 1,"MA": 2 },
"IN": {"DL": 3,"KA": 2 }}
}
Below is the mongodb query I tried, i was able to get to get the count at country level, but not at the state level. please help me in correcting the below query to get data at state level.
db.country_dash.aggregate([
{"$group": {
"_id":"$country",
"state": {"$addToSet": "$state"}
}},
{"$project": {
"_id":0,
"country":"$_id",
"state": {"$size": "$state"}
} }
])
db.country_dash.aggregate(
// Pipeline
[
// Stage 1
{
$group: {
_id: {
city: '$city'
},
total: {
$sum: 1
},
country: {
$addToSet: '$country'
}
}
},
// Stage 2
{
$project: {
total: 1,
country: {
$arrayElemAt: ['$country', 0]
},
city: '$_id.city',
_id: 0
}
},
// Stage 3
{
$group: {
_id: '$country',
data: {
$addToSet: {
city: '$city',
total: '$total'
}
}
}
},
]
);