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

What is the best way to duplicate v-models using :value instead of :value?

When using @input and v-model, or @input and :value, I have noticed different behavior. What is v-model doing differently with :value that I am not able to achieve by only using :value? To demonstrate this difference, I have created an example on jsFiddl ...

Unexpected behavior observed when trying to smoothly scroll to internal links within a div, indicating a potential problem related to CSS dimensions and

Within a series of nested div containers, I have one with the CSS property overflow:hidden. My goal is to smoothly scroll to internal links within this specific div using jQuery. The snippet of code below has worked successfully in previous projects: ...

Is there a way to retrieve a promise from a function that triggers a $http.get request in AngularJS?

Looking for a solution to modify this function: getX: function ($scope) { $http.get('/api/X/GetSelect') .success(function (data) { ... ... }) .error(function (data) { ...

Utilizing the EJS access to retrieve express variables within a JavaScript onload function

When working with variables in an EJS file, you can easily access their values. For example: <h1><%= title %></h1> Now, if you want to use the same 'title' variable in an onload JavaScript function on the same EJS page, how wo ...

Adjust the menu scrollbar position to the right or limit scrolling to within the menu area

$(function() { "use strict"; $(".navbar-toggler").on("click", function() { $(".navbar-toggler").toggleClass("collapsed"); $(".offcanvas-collapse").toggleClass("open"); let menuposition = $("#toggler").offset().left + $("#toggler").width() + ...

Modifying the DOM within a getJSON callback

My current challenge involves fetching data from the YouTube API and displaying it on my website. However, I am facing an issue where the DOM changes made inside the getJSON's callback function are not reflecting on the webpage. Even though I can see ...

Is it possible to show a pop-up window containing aggregated data when the jQuery double-click event

How can I create a pop-up window to display aggregated data when the Double-click event is triggered in jQuery? In my code, each questionId has multiple related reasons. When a user clicks or selects a questionId button/event, the selected questionId will ...

The issue with element.style.backgroundColor not functioning properly within WordPress

Struggling to make the background of a button change upon hover? I've got the code, but it seems to be working everywhere except in WordPress. Check out the code that should be working here: https://jsfiddle.net/TopoX84/3oqgmjb0/ Want to see it not ...

What steps should I take to display a Modal upon a successful Oauth2 redirect?

I am currently working on an older web application that utilizes the portal/portlet architecture. Within the application, I have a feature that loads in a modal when accessed. The modal includes navigation functionality that allows customers to navigate t ...

Issues encountered when utilizing the successCallback function in ag-grid

I'm encountering an issue with a Vue component that has an ag-grid grid (infinite model). I need to access its params in order to use the successCallback method directly within another method in the component, subsequent to setting the datasource. In ...

The lifecycle of a React state in a filtering component

Seeking guidance on handling state updates in a component designed for filtering purposes (such as selecting dates, min/max values, etc). My current setup is as follows: onMinDateChange(minDate) { this.setState({minDate}); }, onMaxDateChange(maxDate) ...

Transform the string property extracted from the API into a JSON object

When making a request to an API, the data returned to the front end is in the following format: { name: 'Fred', data: [{'name': '"10\\" x 45\\" Nice Shirts (2-pack)"', 'price' ...

Learn how to implement Basic Authentication in your Express application using the express-basic-auth package. You can easily trigger login and logout

When it comes to logging out a user who has logged in using basic Auth, I am exploring different options by consulting various sources like: link1 link2 In my application, I have implemented express-basic-auth to secure certain routes. Here is an example ...

Is there a way to determine if a browser's network activity is inactive?

Within an angularJS application, a noticeable delay can be experienced between the user and the server (potentially due to limited bandwidth), resulting in a wait time of approximately 2-500ms when loading a new page. I am considering implementing a metho ...

JavaScript - Capture user input and store it in a cookie when the input field is changed

Any help with my issue would be greatly appreciated. I'm currently working on saving the value of a form input type="text" to a cookie when the input has changed. It seems like I'm close to getting it right, but unfortunately, it's not worki ...

Managing all AJAX success events in one centralized location using jQuery

In a particular situation, I find myself needing to handle all jquery success events in one centralized location. This is because I want a specific function to be called after every ajax success event occurs. While I am aware that I can use $.ajaxComplete ...

The function "xml find" does not exist

After successfully running the following ajax call, I encounter an issue: $.ajax({ url: "services/orders/<%=OrderServices.Action.BULK_SUPPLIER_DISCOUNT%>", data: params, complete: function(xhr) { i ...

Inquiries on VueJS Efficiency

Currently, I am developing a browser extension utilizing Vue Cli with Vue Bootstrap. I have taken steps to optimize my Vue Bootstrap imports by loading only the necessary components and icons for the project. Despite having lazy loaded route components, I ...

What is the best way to layer four images in a 2x2 grid over another image using CSS as the background

I am attempting to place 4 images of the same size on a 5th image defined as the background. Currently, it looks like this: It works perfectly when the height is fixed, but in my case, the height may vary causing this issue: This problem isn't surp ...

Dynamically parallelizing functions with async and arrays

I have recently integrated the fantastic "async" module by caolan into my Node.js project: Below is a snippet of the code in question: exports.manageComments = function(req, res) { var toDeleteIds = []; var deleteFunctions = []; if (req.body. ...