What is the best way to showcase the length of an array belonging to a particular category within an angular application?

My tabs display the number of items in each container they open. Below is the filter for that. I want to show the number of objects inside filtered.length, I think.

Take a look at my Data:

[
{
  "img":"assets/images/gallery/girls-1.jpg",
  "group": "girls",
  "title": "Image 1",
  "desc": "Description",
  "link":""
},
...
{
  "img":"assets/images/gallery/space-2.jpg",
  "group": "space",
  "title": "Image 17",
  "desc": "Description",
  "link":""
}
]

Below is a screenshot of the page. Focus on the numbers within each tab. These numbers represent the amount of images in that category and accordingly, how many will appear on the right side. The implementation for that part is already complete; I simply need to display those numbers programmatically.

https://i.sstatic.net/sS1Kt.jpg

Here is the Filtered HTML I am working with:

<ul ng-init="tab = 1" class="list-group">
        <li ng-class="{active:panel.isSelected(1)}">
            <a class="list-group-item" ng-click="panel.selectTab(1); groupFilter = {}">All
            <span class="badge badge-primary">{{galleries.length}}</span></a>
        </li>
        <li ng-class="{active:panel.isSelected(2)}">
            <a class="list-group-item" ng-click="panel.selectTab(2); groupFilter ={group:'nature'}">Nature
            <span class="badge badge-success"><!--The amount of items of group Nature. 7 --></span></a>
        </li>
        ...


  </ul>

Thank you in advance for your help. I'm currently learning Angular.

Answer №1

$scope.calculateCategoryLength = function(category) {
  var total = 0;
    angular.forEach($scope.category_array, function(item){
        total += item.group == category ? 1 : 0;
    });
    return total; 
}

Use the function like this:

{{calculateCategoryLength("nature")}}

This will provide you with the count of items in the specified category.

Answer №2

Give this a shot

let itemCounts={};
for(let x = 0 ; x < itemList.length ; x++) {
  itemCounts[itemList[x].category] = itemCounts[itemList[x].category] ?   itemCounts[itemList[x].category]+1 : 1;
}
console.log(itemCounts);

This code snippet will display

{ animals: 4, books: 6, movies: 9, sports: 2 }

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

Updating React state using a form input

Seeking assistance on retrieving form values and storing them in state. Despite following various guides (mostly in class style react), I keep encountering the same error: "Nothing was returned from render. This usually means a return statement is m ...

Evaluating the conditional rendering of a React child component using Jest and Enzyme

I am currently working on expanding the test coverage for this particular file: import React, { useContext } from 'react'; import UserContext from '../../contexts/user'; import styles from './index-styles.scss'; const UserLog ...

Tips for troubleshooting an Angular error when no specific information is provided

I'm encountering an error `ERROR Error: "[object Object]" in my console and my app is displaying a white screen. Everything was working perfectly fine before, and I can't pinpoint any changes that may have caused this issue. The error appears to ...

Error message indicating that the event "OnkeyDown" is not in sync within the React application

Hey everyone! I'm a beginner in web development and I'm struggling to understand why the event "OnKeyDown" is triggered the second time. My task involves changing (increasing, decreasing) parts of a date (day, month, year, hour, minutes, seconds) ...

typescript unable to establish a connection with postgres.SqlClient

My attempt to establish a connection with a postgresSQL database in typescript is not going smoothly. Unfortunately, I am encountering difficulties without a clear indication of the cause. Despite the absence of an error log output, I tried using manual c ...

Linking query branches without encountering the "Exceeded the number of hooks rendered during the previous render" error

This apollo client utilizes a rest link to interact with 2 APIs. The first API returns the value and ID of a record, while the second API provides additional information about the same record. I combine this information to render the content without using ...

What is the purpose of uploading the TypeScript declaration file to DefinitelyTyped for a JavaScript library?

After releasing two JavaScript libraries on npm, users have requested TypeScript type definitions for both. Despite not using TypeScript myself and having no plans to rewrite the libraries in TypeScript, I am interested in adding the type definition files ...

Error encountered in VueJS 2: Uncaught ReferenceError: _ is not defined when using debounce

I'm attempting to implement a debounce function with a 500ms delay. I found guidance in the documentation provided here. methods: { // Retrieve necessary data for the page fetchData: _.debounce(function () { this.$http. ...

Interactions within nested controllers

As a newcomer to Angular, I have been searching for a suitable solution to the following issue but have not found one that meets my needs. I have a very simple modal dialog controlled by ModalDialogCtrl which contains an edited object, such as Rabbit or Do ...

An issue arose with Java script parsing during the nightly Jenkins build following the upgrade to Sonar 4.3.2

Since upgrading Sonar to version 4.3.2 from 3.4, we have encountered a JavaScript parsing error during Jenkins nightly builds. Everything was functioning properly in the previous version. The Sonar runner is still on version 2. Any advice on how to resolve ...

Issues with Datepicker functionality in Bootstrap 5 are causing it to malfunction or not display

I am having trouble incorporating a timepicker on my webpage with bootstrap 5. The calendar feature isn't loading properly, preventing me from selecting any dates. I'm unsure if the issue lies with an error on my end or if the plugin isn't c ...

Adjust checkbox based on selection from <select> option

In my scenario, I have a selection process where the ID of the <option> element is sent to a .php file. Afterwards, based on some database checks, I need to dynamically check or uncheck a checkbox. Everything seems to be in place except for this last ...

What is the proper usage of main.js and main.css within the skeleton portlet project that is created by the Liferay 6.0.6 plugin SDK?

Is it a good practice to include portlet-specific JS or CSS in them only if <portlet:namespace /> works within them? Should I rely on unique function/variable names or class names instead? ...

The AJAX request successfully retrieves data, but the page where it is displayed remains empty

I have come across similar questions to mine, but I have not been successful in implementing their solutions. The issue I am facing involves an AJAX call that is functioning correctly in terms of receiving a response. However, instead of processing the re ...

Create a line graph overlaying an area chart

I am currently working on developing a chart using D3js v5.12.0. So far, I have successfully created an area chart with the year variable on the X-axis and the earth_footprint variable on the Y-axis. You can find the data for this chart at the following ...

Using Twig: Transfer the content of a textfield as a parameter in the routing

I have a task of redirecting to another page while passing along the value from a textfield. Here is my current code: {% extends "base.html.twig" %} {% block body %} <button onclick="host()">Host the session</button> <button onclic ...

Tips on retrieving the API response using AJAX

Currently, I am attempting to retrieve the API response from Flickr using Ajax in my application built with Laravel. To accomplish this, I have established a specific Route and function dedicated to handling API calls. //Route.php Route::post('/getlo ...

At times, an InvalidArgumentError occurs stating: "The 'handle' parameter must be a string."

I have incorporated 'React-google-login' into my React project and now I am working on an automated test to make sure it functions correctly. try { await driver.get("http://localhost:3000/"); await driver.wait(until.elementLocated(By.xpath(` ...

Calculating the frequency of selections for each option in a dropdown menu

I am currently in the process of developing a form to assist with classroom observations. The main objectives of this form are as follows: The form must be entirely client-side, so I have opted to utilize JavaScript. It should track the total number of i ...

Confirm the validity of only the fields that are currently displayed

How can I validate only the visible fields for a Condominium and Room option using Radio buttons, without validating any hidden fields? <div id="condo_display" style="display:none"> <input type="text" name="condo_name" required> </di ...