Vue Error: The method "reduce" is not a function

Currently implementing Vue.js with Typescript and aiming to utilize reduce for summing up the values of desktopCnt and mobileCnt from the deviceCount array to display their total numbers.

The deviceCount array structure is as follows:

[
    {
       "_id":{
          "device":1
       },
       "mobileCnt":451
    },
    {
       "_id":{
          "device":0
       },
       "desktopCnt":210
    },
    {
       "_id":{
          "device":2
       },
       "mobileCnt":88
    },
    {
       "_id":{
          "device":10
       },
       "mobileCnt":57
    }
]

An example of the code implementation:

 <template>
   <span>
    PC :
    {{ deviceCount.reduce((r, a) => (r += a.desktopCnt), 0) }}

    Mobile :
    {{ deviceCount.reduce((a, { desktopCnt }) => a + mobileCnt, 0) }}
   </span>
 </template>

Script section for fetching data:

<script lang="ts">
import Vue from 'vue';
import axios from 'axios';
import { DeviceCount } from '../../components/models';

export default Vue.extend({
  data() {
    return {
      deviceCount: [] as Array<DeviceCount>,
    };
  },
  created() {
    this.initData();
  },
  methods: {
    async initData() {
     // Fetching data and setting it to deviceCount array
    },

    async getDeviceCount() {
      // Processing fetched data here
      return processedData;
    },
  },
});
</script>

Edit made on the interface: interface DeviceCount

interface DeviceCount {
    _id: {
      device: string;
    };
    avgPrice: number;
    avgQuantity: number;
    buyRatio: number;
    goodsCnt: number;
    quantity: number;
    revenue: number;
    totalEvents: number;
    uniqueEvents: number;
    users: number;
    mobileCnt: number;
    desktopCnt: number;
}

console.log(item) in script https://i.stack.imgur.com/ebPEa.png

Despite trying different approaches, encountering the error message:

TypeError: _vm.deviceCount.reduce is not a function

Troubleshooting assistance requested to identify the origin of this error. Thanks!

Answer №1

Utilize computed properties instead of inserting lengthy javascript expressions directly into the template for better readability and maintainability:

 <template>
   <span>
    PC :
    {{ desktopCount}}

    Mobile :
    {{ mobileCount }}
   </span>
 </template>

Here is an example implementation in the script section:

export default Vue.extend({
  data() {
    return {
      deviceCount: [] as Array<DeviceCount>,
    };
  },
computed:{
   desktopCount(){
   return this.deviceCount.reduce((r, a) => (r += (+a.desktopCnt ?? 0)), 0)
   },
  mobileCount(){

  return this.deviceCount.reduce((a, { mobileCnt}) => a=a + (+mobileCnt ?? 0), 0)
  }

}
...

The usage of a.property ?? 0 ensures that 0 is returned if the property is undefined or null to prevent getting a NaN result.

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

The data type 'boolean' cannot be assigned to the type 'StoryFnReactReturnType' in a React Storybook project using Typescript

I am currently working on setting up a Button component with Storybook in typescript. I am referencing The Documentation and using this specific example. Below is my Component and its story: components/Button.tsx: import {FC} from 'react'; exp ...

Generating components dynamically will consistently delete the most recent instance

In my project, there is a scenario where a child component and a parent component are involved. The parent component dynamically renders the child component on demand and keeps track of it in an array. When the child component needs to be removed, it emits ...

Specify a non-string value (such as primitives, object, or expression) for checkbox true-value and false-value

I am experiencing difficulty in changing the v-model value to anything other than a string when the checkbox is checked or unchecked. https://jsbin.com/haqofus/edit?html,console,output <div id="app"> <div><input type="checkbox" v-model ...

Steps for launching a hyperlink in a browser on Vue Native

I'm having trouble finding information on how to properly use the Linking component in react-native. The resources available are limited, and I'm not sure if I am implementing it correctly... Below is what I have in my template: <nb-button :o ...

Having trouble with Vee-validate Basic example - undefined errors issue

I've been struggling to get a basic form validation page working with vee-validate. Something seems to be going wrong, but I can't pinpoint the exact issue. Why am I seeing the error: errors not defined. <!DOCTYPE html> <html> < ...

The npm start command is unable to recognize the tsx file

I recently attempted to create a React app and incorporate TypeScript into it. However, upon running the app, I noticed that npm start was not recognizing the TypeScript file and failing to automatically generate tsconfig.json. Here is the sequence of ste ...

Tips for implementing <mat-progress-bar> in .ts file when making API service requests with Angular

I'm currently utilizing an API call to retrieve an image from a service, and I would like to display a progress bar while the image is being fetched. It seems that I need to incorporate the progress bar within the service as the image data is returned ...

Unveiling the Power of Ionic and React for Component Repetition

I'm having trouble figuring out how to repeat my component multiple times using react in Ionic. Can someone assist me with this? Here's an example: In my Component.tsx file, I have the following code: import React from 'react'; import ...

Steps to integrate Framework7 with Ionic 2

Is there a way to incorporate framework7 into a ionic2 project? I have successfully installed framework7 in my ionic2 project using the following command: npm i framework7 --save My next step is to add the typescript definition to the project by downloa ...

Vue JS - Issue with rendering <tr> and <td> elements in table component

I have created a custom table component using vue.js: <template> <div> <table class="table border"> <thead> <tr> <td>header 1&l ...

What is the method for returning a string array?

My query is about how to return a string[]. Currently, TypeScript is throwing an error because each element of the array has a type of ( T[keyof T] extends readonly (infer InnerArr)[] ? InnerArr : T[keyof T] ). How can I accept the 'property' arg ...

Attempting to grasp the concept of implementing FormArray

When I execute the following code: this.formArray = new FormArray([ new FormControl(''), new FormControl(''), ]); formControlA() { return this.formArray.at(0); } formControlB() { return this.formArray.at(1); } and then use it ...

Throttle the asynchronous function to guarantee sequential execution

Is it possible to use lodash in a way that debounces an async function so it runs after a specified delay and only after the latest fired async function has finished? Consider this example: import _ from "lodash" const debouncedFunc = _.debounc ...

What is the process for incorporating a Static Class into a Declaration File in TypeScript?

I'm in the process of developing a UMD library using TypeScript. The first class I have created is a static one with a method. The name of my Library is SuperLib and here is the code snippet: export class Security { static userExists ( user: string ...

Change the format of the array from the initial array to the new array structure

I have a multi dimensional array that I need to convert into the array2 structure. I've tried various methods, but all of them have resulted in bulky code and lots of iteration. Is there an easier way to accomplish this task? I am new to Angular and ...

Using React with Typescript: What is the best way to implement useMemo for managing a checkbox value?

I am currently developing a to-do list project using React and Typescript. At the moment, I have successfully implemented the functionality to add new to-do items via a form and delete them individually. Each item includes a checkbox with a boolean value. ...

Is there a way to assign API data as inner HTML using Lit?

Need help setting inner html of html elements with a get request Any suggestions on how to achieve this? import { LitElement, html, css } from "lit"; import { customElement } from "lit/decorators.js"; import axios from "axios" ...

Retrieve information from an XML document

I have some XML content that looks like this: <Artificial name="Artifical name"> <Machine> <MachineEnvironment uri="environment" /> </Machine> <Mobile>taken phone, test when r1 100m ...

Creating a sophisticated union type by deriving it from another intricate union type

I have a unique data structure that includes different types and subtypes: type TypeOne = { type: 'type-one', uniqueKey1111: 1, }; type TypeTwo = { type: 'type-two', uniqueKey2222: 2, } type FirstType = { type: 'first&apo ...

I am encountering an issue where my Vue navbar is successfully changing the route but not updating the corresponding router-view

I have been working on a single-page application using Vue and I encountered an issue with the navbar when navigating through routes. The problem is that after the first click on a navbar item, the route changes successfully but the router-view does not up ...