Count the number of items in a JSON array in AngularJS with a specific ID

To get the total count of articles in a JSON array, I use the following method:

Home.html

<div ng-controller="pfcArticleCountCtrl">Number of Articles {{articlecount.length}} items</div>

Controllers.js

// Calculate total number of articles
pfcControllers.controller('pfcArticleCountCtrl', ['$scope', 'pfcArticles', function ($scope, pfcArticles) {
$scope.articlecount = pfcArticles.query();

}]);

Services.js

// Retrieve articles by ID
pfcServices.factory('pfcArticles', ['$resource', function ($resource) {
    return $resource('https://myrestcall.net/tables/articles/:articleID', { articleID: '@id' },
    {
        'update': { method:'PATCH'}
    }
    );
}]);

Now, in addition to displaying the overall count, I also want to show the number of articles by category. Here is an example data set:

[
{
"id": "66D5069C-DC67-46FC-8A51-1F15A94216D4",
"articletitle": "article1",
"articlecategoryid": 1,
"articlesummary": "article 1 summary. "
 },
{
"id": "66D5069C-DC67-46FC-8A51-1F15A94216D5",
"articletitle": "article2",
"articlecategoryid": 2,
"articlesummary": "article 2 summary. "
}, 
{
"id": "66D5069C-DC67-46FC-8A51-1F15A94216D6",
"articletitle": "article3",
"articlecategoryid": 3,
"articlesummary": "article 3 summary. "
},   
{
"id": "66D5069C-DC67-46FC-8A51-1F15A94216D7",
"articletitle": "article4",
"articlecategoryid": 1,
"articlesummary": "article 3 summary. "
}, 
]

In this scenario, the total count is 4, with 2 articles in Category 1. To display this information on a page, it should look like this:

Category 1 (2) Category 2 (1) Category 3 (1)

Total Articles (4)

How can I count the number of articles per category?

Answer №1

To create an object with the cat ID as the name and the count as the value, one could utilize the reduce method:

$scope.articleByCat = articles.reduce(function (prev, item) {

    if ( !! prev[item.articlecategoryid]) {
        //category already exist -> increment
        prev[item.articlecategoryid]++;
    } else {
        //category does not exist -> init
        prev[item.articlecategoryid] = 1;
    }
    return prev;
}, {});

This can be accessed through your scope and displayed using ng-repeat

<div ng-app='article' ng-controller='ArticleController'>
 <ul>
     <li ng-repeat='(key, value) in articleByCat'>Category {{key}} : {{value}}</li>
    </ul>
 </div>

Here is a live example on jsfiddle

Answer №2

To begin, organize the elements in the array var data = [ ]; based on a specific criterion.

data.sort(customSort);

function customSort(a, b) {
  if (a.articlecategoryid < b.articlecategoryid)
     return -1;
  if (a.articlecategoryid > b.articlecategoryid)
    return 1;
  return 0;
}

Next, identify and count any duplicate values in the array.

var current = null;
var count = 0;
for (var index = 0; index < data.length; index++) {
    if (data[index].articlecategoryid != current) {
        if (count > 0) {
            document.write('Category '+ current +' occurs '+ count + ' times<br>');
        }
        current = data[index].articlecategoryid;
        count = 1;
    } else {
        count++;
    }
}
if (count > 0) {
    document.write('Category '+ current +' occurs '+ count + ' times');
}

For a practical example, refer to the demonstration provided here.

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 execute a function before showing an alert in a $.post() callback?

Just to clarify, the code I'm working with is not original to me; I am simply making some interface adjustments using a plugin for an existing system. The task at hand involves creating a plugin that utilizes blockUI (yes, a plugin within a plugin) t ...

Next.js is experiencing issues with the build process

I encountered an issue while working on a Next.js project with NextAuth.js. The problem arises when I try to define my authOptions, as a TypeScript error indicates that the object is not compatible with the expected type for AuthOptions. Here's the sn ...

Utilizing a search feature to navigate through JSON data in a Ruby on Rails

I'm currently integrating JSON data into my Rails application. I am aiming to implement a search functionality that can look up the name column in the JSON data. Are there any gems or resources available that could assist me in accomplishing this? da ...

Uncover the hidden treasures within an array of objects using Postman

My goal is to extract the Id value from an array of objects using Postman and then store it as an environment variable. I have a script that works with JSON responses that are objects, but not with arrays of objects (my array only has one object). var dat ...

Issue with Dynamic Image Path in Require Function: Unable to locate the relative module

I've been struggling with an error in VueJs require function for the past two days. I'm attempting to pass a prop to the Home component and then display the image. Home.vue <template> <BlogPost :post="welcomeScreen"/> <B ...

Leveraging oEmbed - JSON data (within client-side JavaScript)

Is it feasible to utilize an oembed provider that solely produces json and xml outputs on the client side using javascript (through a $.ajax request to the provider)? Do we need to rely on oembed providers that enable a jsonp callback in javascript for th ...

Guide on how to toggle disabled input text box upon checking checkbox using JavaScript

When the checkbox next to the appended text box is checked, I want to disable that text box. The hard-coded text box is already disabled when its checkbox is checked. You can see the actual outcome by running the code snippet or check out the screenshots b ...

Getting the user's name and country using `auth().createUserWithEmailAndPassword` is a simple process

Hey there fellow developers. I'm fairly new to react native and I'm trying to implement firebase authentication for a project. However, I'm stuck on how to include user name and country when using the standard auth().createUserWithEmailAndPa ...

Why is the image popup feature not functioning properly? What could be causing the issue?

I'm experiencing issues with the functionality of my HTML file and image popup. I've attempted to troubleshoot it multiple times without success. Here is a code snippet for reference: You can view and run the code on CodePen: Open <html> ...

Tips for incorporating the camera from fbxloader into your three.js scene

I am currently utilizing fbxloader from three.js to incorporate a model into my scene. I have noticed that the most recent version of fbxloader.js (https://github.com/mrdoob/three.js/blob/master/examples/js/loaders/FBXLoader.js) has the capability to read ...

Unraveling the Mysteries of Node.js Application Logging

We've been having smooth sailing with our Kube cluster on AWS, but there seems to be a recurring issue with our Node app crashing and generating repetitive logs from our instances... I've scoured the internet for solutions but haven't had m ...

I am experiencing difficulty with the Click() operation in Selenium web driver as it is not successfully redirecting me to another page

Hello everyone, I could really use your assistance with a problem I'm facing. WebElement wb=driver.findElement(By.name("NavHeader1$tabs$ctl00$btnNavHeaderTab")); Actions act=new Actions(driver); act.moveToElement(wb).perform(); ...

Using CoffeeScript with Visual Studio 2012

After following the installation steps at , I successfully installed CoffeeScript on my system. Everything was running smoothly as the coffee code was compiled to JavaScript whenever I pressed ctrl + s. Recently, a colleague retrieved my code from the so ...

Duplicate the image from a specific div to another div, ensuring that only one clone is created

I'm trying to replicate an image in multiple spots within a frame, but I can only manage to get one instead of many. Can someone please tell me what I'm doing wrong? I am creating a map of terrain where I need to clone images from one div to anot ...

Unlocking the contents of an array from a separate file in Next.js

I am developing a Quiz App that consists of two main pages: takeQuiz.js and result.js. My goal is to transfer the data from the multiple-choice questions (mcqs) in takeQuiz.js to be accessible in result.js. Utilizing router.replace(), I ensure that once th ...

Accessing the jQuery Ajax success variable

I have a PHP function that returns an array with an element error containing the value 'ERR': var updatePaymentType = function(plan_pt_id, pt_id){ var error = null; var data = new Object() data["function"] = "update"; ...

Callbacks and scope in MySQL操作callbacks and scopeMySQLcallbacks

I'm encountering challenges while utilizing node-mysql to construct a web API with express. I have a file named ./lib/handlers/list.js, which is successfully loaded (using require('./lib/handlers/list.js')(app)): var error = function(res){ ...

Passing arguments to an external function in jQuery from a dynamically loaded Ajax page

Despite its confusing title, the issue at hand is actually quite simple. My homepage contains a script that loads an external PHP file for a specific section of my website. Within this PHP file, I need to call a function from the main JavaScript file (th ...

Encountering an issue of receiving "Undefined" while attempting to access constant data from a ReactJS file within my NodeJS

I am currently working on a file named check-rates that stores useStates() which are inputs provided by users. These inputs are essential for me to calculate and provide an estimated value for their shipment using the DHL API. In my nodejs express server, ...

Pagination activates on the second tap

Check out my example on jsFiddle: https://jsfiddle.net/0se06am5/ class Pagination extends React.Component { constructor(props) { super(props); this.state = { current: 1 }; this.items = ['a', 'b', 'c&ap ...