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

Building upcoming records in Firestore

Seeking advice on the best approach for managing future milk orders in my Vue.js application. In this app, customers can subscribe to order milk 1, 2, or 7 times a week for a specific period (e.g. 90 days). The challenge lies in determining how to handle ...

Struggling with declaring generic types in TypeScript can be a challenge

Struggling with declaring the type while creating a hook named useUpdate, here's the code: type CallBack<T extends readonly any[]> = ( ...args: T ) => void | (() => void | undefined); function useUpdate<T extends readonly any[]>( ...

Axios does not appear to be transmitting cookies

In my development setup, I am using two separate applications: a server-side application built with Laravel and a client-side application using VueJS. The Vue app consumes the API provided by the Laravel app to interact with the backend functionalities. A ...

The proper method for retrieving FormData using SyntheticEvent

I recently implemented a solution to submit form data using React forms with the onSubmit event handler. I passed the SyntheticBaseEvent object to a function called handleSubmit where I manually extracted its values. I have identified the specific data I n ...

Typescript - ensure only one specific value is in an array of length N

Is there a way to require the 'foo' literal, while allowing the array to have any shape (i.e. not using an X-length tuple with pre-defined positions)? type requireFoo = ??? const works: requireFoo = ['bar','foo'] //This shoul ...

What is the method for substituting one text with another using two-way data binding?

I implemented two different cases in my Mat-Table. When there is no data, the user will see a message saying "No Data Found". However, if the user enters text in the filter search, the "No Data Found" message should be hidden and replaced with the entered ...

Retrieve data upon component mounting and deactivate the query in React-query

When navigating to a search result page, query parameters are passed to useQuery. I want the data to be fetched only when the user clicks the "Search" button after changing the search prompt. I attempted to use enabled: false and call refetch() on button ...

Setting the content-type for static assets in NuxtJS

I'm trying to use the Nuxt built-in server to serve the static file /.well-known/apple-app-site-association with a content-type of application/json. Unfortunately, because the file does not have a .json extension, it is returning as application/octet- ...

Having trouble moving to a different component in Angular?

In my application, I am facing an issue with navigating from List to Details component by passing the ID parameter. It seems that there is no response or error when attempting to call the relevant method. Below, you can find the code snippets related to th ...

Emphasize x-axis heading in a Highcharts graph

In my Highcharts bar graph, I am looking for a way to dynamically highlight the x-axis label of a specific bar based on an external event trigger. This event is not a standard click interaction within the Highcharts graph. Currently, I have been able to r ...

What is the best way to enhance a react-bootstrap component with TypeScript?

Currently, I am utilizing <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6f1d0a0e0c1b420d00001b1c1b1d0e1f2f5e415f415f420d0a1b0e415e5b">[email protected]</a> and delving into the development of a customized Button ...

Retrieve all articles from a user using the TypeORM - findAll function

Is there a way to retrieve all articles of a specific user using the TypeORM package? In Sequelize, I have the following function: async findAllByUser(userUuid: string, findOptions: object): Promise<Article[]> { return await Article.findAll< ...

Comparing "const" and "Vue.component": Understanding the Distinctions

I am new to the world of Vue framework and finding myself struggling with the basics. Currently, I am facing a challenge in creating reusable components. My current approach to creating these components is as follows: Vue.component('SomeReusableComp ...

Invoking a Vue method within a Laravel blade template

In my Laravel project, I have a blade that is loading a Vue component successfully. However, I am facing an issue where calling a method in the Vue component from a select box in the blade is not working as expected. Despite having a method call set up to ...

I am having trouble converting HTML code to PDF using vue-html2pdf

Currently working on a project in vuejs that requires the use of vue-html2pdf. Interestingly, when I input text within the <section>something</section> tag, my PDF is successfully generated. However, if I attempt to add text inside the <sec ...

A warning message from Laravel: "Template compilation error in Vue"

I'm experiencing an error when compiling Vue. I've added the following code snippet at the bottom of the page: <script src="{{ asset('js/app.js') }}"></script> <script type="text/javascript"> @yield(& ...

How to Send Data with NodeJS by Utilizing the Finish Event

Is there a way to retrieve the JSON data sent during the nodejs finish event? This is how I send the JSON data: oResponse.json({ version: "1.0.0", author: "Someone", contributors: "also Someone" }); I would like ...

Enhance Your Vue Tables with Unique Custom Filters

I'm currently working on implementing https://github.com/matfish2/vue-tables-2 in Vue 2.1.8. Everything seems to be functioning flawlessly, but I need to incorporate custom filters to format certain fields based on their values. In my options object ...

Create an interface object in TypeScript with no initial properties

I'm currently developing an app with angular 5 (TS) and I've encountered a problem while trying to initialize an empty object of my interface. The solution that I found and attempted is as follows: article: Article = {} as Article; However, ...

Vue.js encountered a problem with chokidar stating: "Error: EBUSY: resource busy or locked, lstat 'C:hiberfil.sys'"

Description Whenever I execute the command npm run serve, I encounter the following error: ERROR Failed to compile with 1 error 15:34:19 This dependency was not found: * ... in ./node_ ...