What is the best way to show distinct items and their frequencies from an array of objects in Vue.js/JavaScript?

I have been developing an inventory management application using Vuejs, and I am facing a JavaScript-related challenge in my project. The issue revolves around handling data that includes user information retrieved from a form, as well as static categories and locations for selection.

My current task involves extracting unique categories and counting how many times they appear, with the desired output being an array of objects structured like this:

[{title: 'Books', amount: 3 }, {title: 'Records', amount: 1 }, ...]

I suspect that the problem lies within the scope of my implementation.

Data

userData: {
        items: [
          {
            itemName: 'test book',
            category: 'Books',
            location: 'Kitchen',
          },
          ...
        ],
        categories: ['Books', 'Movies', 'Records', 'Furniture'],
        locations: ['Basement', 'Garage', 'Kitchen'],
      },

I have managed to achieve the desired outcome for 'Books' but need assistance in generalizing it for all categories. Currently, my code displays the total count of items under the 'Books' category instead of displaying counts for each unique category.

The following method/function is where I'm struggling:

filteredItems = items.filter((item) => item.category === 'Books').length

In my logic, I need to find out what should replace the hardcoded 'Books' string in the filter function above for dynamic results across all categories.

For further clarity on the issue, please refer to the screenshot below:

https://i.stack.imgur.com/wwUpD.png

method/function

   convertedCategories() {
      const items = this.userData.items
      const filteredItems = items.filter((item) => item.category === 'Books').length

      function getItemCountOfCategory(categoryName) {
        return filteredItems
      }

      function convertCategoriesIntoCards(categories) {
        return categories.map((el) => {
          return {
            title: el,
            amount: getItemCountOfCategory(el),
          }
        })
      }

      return convertCategoriesIntoCards(this.userData.categories)
    }

If you need additional clarification or assistance regarding the specific line of code related to this query, please feel free to ask!

Answer №1

Here is a suggested solution.

   generateCards() {
      const data = this.userData.data
      function getCountOfDataCategory(categoryName) {
        return data.filter((item) => item.category === categoryName).length
      }
      function convertDataIntoCards(categories) {
        return categories.map((el) => {
          return {
            title: el,
            quantity: getCountOfDataCategory(el),
          }
        })
      }
      return convertDataIntoCards(this.userData.categories)
    },

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

methods for pausing music through a toggle button in a React JS application

I am facing an issue with the following shortcode for playing a song on a toggle button. The problem occurs when I try to pause the music and it does not stop as expected. import { React, useState } from 'react'; import './audio.css&apos ...

I require the capability to retrieve JSON data from beyond the confines of the function

After searching, I was unable to locate it. In my possession is a javascript file and a separate file named data.json. data.json { "today": [ { "id": 1, "title": "Note 1", "date": "21.05.2019", "text": "Lorem ipsum dolor sit ...

Modify the events JSON URL when the Full Calendar changes its display period

Whenever I switch between months or weeks, I need the JSON URL link to update accordingly. For example: The initial JSON URL is: /json/?start=2018-01-28&end=2018-03-10 When moving to the next month, the URL changes to: /json/?start=2018-02-25&am ...

What is the most efficient way to organize an array by date?

Here is the data I have: const data = [{date: "2022-05-10 13:36:00", open: 155.535, low: 155.4, high: 155.67, close: 155.44}, {date: "2022-05-10 13:35:00", open: 155.23, low: 155.2102, high: 155.62, close: 155.53}, {date: "2022-05 ...

Should the request be sent to the parent or child component?

When a page is divided into various components, the data for each component is fetched asynchronously. Therefore, the parent component should trigger the request and pass it on to the child component, or alternatively, the request can be directly sent to ...

What is the process for AngularJS to automatically populate the initial tag value in an SVG template?

I'm currently working on an AngularJS directive that needs to update different attributes within an svg tag. angular.module("complexNumbers") .directive("cartesianPlane", function() { return { restrict: "E", scope: { }, templateUrl: " ...

What is the syntax for defining parameters in an overloaded arrow function in TypeScript?

Trying to create an async arrow function that can handle a single image object or an array of image objects. I'm new to TypeScript overloading and may be approaching this the wrong way. Here's what I've come up with: type ImageType = { ...

I'm attempting to create a button that changes to a bold red color when the condition is met

I am currently working on developing web applications using the Pixabay API. My goal is to allow users to mark an image as a favorite and have the heart icon change color to red accordingly. However, I seem to be facing issues with this functionality. To ...

No Backend Detected for Tensorflow.js in Node

I've been attempting to develop a Discord bot that utilizes the @tensorflow-models/qna library, but I've hit a roadblock for the past 4 hours. Every time I run the script below: const qna = require('@tensorflow-models/qna'); (async () ...

Changing the value of a variable after iterating through an array in JavaScript

I'm just getting started with programming and teaching myself. I'm struggling to grasp how to update a variable by iterating through an array. Here's an array containing the best pies, each with its own price: [blueberry, strawberry, pumpk ...

Leveraging the power of ng-describe for comprehensive end-to-end testing using protractor

Recently, I stumbled upon a fantastic ng-describe package that simplifies the process of writing unit tests for AngularJS applications. It eliminates the need to remember and write all the boilerplate code required to load, inject, mock, or spy. Has anyon ...

What is the best way to store textarea information into a session using the jQuery AJAX post method in Codeigniter?

I am having trouble saving the text from a textarea to the Controller session using jQuery AJAX post method in Codeigniter Smarty. I am unable to save the data to the session. Can someone please provide me with guidance and a detailed example of how to ach ...

I am experiencing an issue with my jQuery loop code not functioning properly when using the .each method within the loop

I am struggling with the following code. <input type="text" name="1" class = "inp<?=$p?>"> <input type="text" name="2" class = "inp<?=$p?>"> <input type="text" name="3" class = "inp<?=$p?>"> <input type="text" na ...

Is there a way to click on a button and have its background color change randomly each time?

I am facing an issue with a button on my HTML page. When the button is clicked, I want its background color to change to a random different color. However, despite trying various sources, I am unable to get it right. It seems like I am not placing the code ...

Executing `console.log()` in Windows 8 using JavaScript/Visual Studio 2012

Whenever I utilize console.log("Outputting some text") in JavaScript within Visual Studio 2012 for Windows 8 metro development, where exactly is the text being directed to? Which location should I look at to see it displayed? Despite having the "Output" pa ...

Effective ways to resolve the ajax problem of not appearing in the console

I am facing an issue with my simple ajax call in a Java spring boot application. The call is made to a controller method and the returned value should be displayed in the front-end console. However, after running the code, it shows a status of 400 but noth ...

Trigger a Nuxt/Vuejs event upon completion of rendering all page components

Is there a way to trigger an event after all components on a page have finished rendering? I've attempted using the page mounted event, but it only fires the first time. I need an event to be triggered each time the route changes on the client side an ...

The issue arises when the Javascript function is triggered twice, resulting in only 3 out of 4

I'm currently working on a JavaScript calculator project. Everything is running smoothly except for the add() function (subtraction, multiplication, and division are all functioning properly). Additionally, when I hit "=" it displays the answer twice ...

Using Angular's $http service to send a file to a web API endpoint from a post function

I'm facing an issue with uploading a javascript file or transmitting a javascript file to a post function. On the client side, I am using angularjs $http service to send the data as follows: $http({ method: "POST", ...

What steps can I take to make sure a particular node is successfully loaded and ready for use using JavaScript/jQuery?

When making a reservation at a hotel using the CJS Chrome extension, I am attempting to extract information about available rooms and rates both when the page loads and when the user changes dates. My current method involves injecting JavaScript into the p ...