Angular: Finding the total number of Objects containing a particular value

In my JSON database, I have a collection of objects where each one is assigned a specific value: either a, b, or c.

[
  {
    "id": 1,
    "category": "a"
  },
  {
    "id": 2,
    "category": "b"
  },
  {
    "id": 3,
    "category": "c"
  },
  {
    "id": 4,
    "category": "a"
  },
  {
    "id": 5,
    "category": "a"
  },
  {
    "id": 5,
    "category": "b"
  }
]

I want to show the following information:

There are a total of 6 items: a x 3, b x 2, and c x 1.

To calculate the total number of items, I know I can use objectsinmyjsondatabase.length.

My question is, how can I determine the number of objects that have a specific value?

Answer №1

To create a function, follow these steps:

calculateTotal(character) {
  return this.items.filter(item => item.type === character).length;
}

Now, you can use the function by calling: this.calculateTotal('b');

Answer №2

If you're looking for a solution, consider implementing the map-reduce technique. Below is a quick and effective solution that may just address your issue.

var data = [
  {
    "id": 1,
    "category": "a"
  },
  {
    "id": 2,
    "category": "b"
  },
  {
    "id": 3,
    "category": "c"
  },
  {
    "id": 4,
    "category": "a"
  },
  {
    "id": 5,
    "category": "a"
  },
  {
    "id": 5,
    "category": "b"
  }
];

// Extract all categories from the data
var categories = data.map(function(x) { return x["category"]; });

// Calculate the count of items in each category
var countByCategories = categories.reduce(function(x, y) {
    if (typeof x !== "object") {
       var reduced = {};
       reduced[x] = 1;
       reduced[y] = 1;
       return reduced;
    }
    
    x[y] = (x[y] || 0) + 1;
    return x;
});

// Build the final string as desired
var categoryStrings = [];
for (var category in countByCategories) {
   categoryStrings.push(category + ' x ' + countByCategories[category]); 
}

var msg = 'Total items: ' + categories.length + '. ';
if (categoryStrings.length > 2) {
   msg = categoryStrings.slice(0, -1).join(', '); 
   msg += ' and ' + categoryStrings.slice(-1);
} else {
   msg = categoryStrings.join(', '); 
}

// Display the results
console.log(msg);

Answer №3

If you need to tally up items with specific values, you can achieve this with the following method:

let items = [
    {
        "id": 1,
        "category": "a"
    },
    {
        "id": 2,
        "category": "b"
    },
    {
        "id": 3,
        "category": "c"
    },
    {
        "id": 4,
        "category": "a"
    },
    {
        "id": 5,
        "category": "a"
    },
    {
        "id": 5,
        "category": "b"
    }
];
var countedItems = new Array();
items.filter(function (item) {
    var found = countedItems.some(function (el, index) {
        if (false == (item.category === el.category)) {
            return false;
        }
        countedItems[index].count = countedItems[index].count + 1;
        return true;

    }, countedItems);
    if (false === found) {
        countedItems.push({category: item.category, count: 1});
    }
}, countedItems);
console.log('There is a total of ' + items.length + ' items: '
    + countedItems.map(function (item) {
        return item.category + ' x ' + item.count;
    })
);

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 reason Angular is unable to locate a controller for a directive in an external file?

As a newcomer to Angular, I'm struggling to comprehend John Papa's recommendations. His guidelines suggest placing controller logic inside directives, but this approach doesn't seem intuitive to me. Despite my efforts to implement it myself, ...

The array filtering functionality is not functioning as intended

Struggling with correctly filtering data in JavaScript. Here's an example where var1 = 20, var2 = 10, var3 = 30, var4 = 40. This is the code snippet: var variables = ['var1', 'var2', 'var3', 'var4'], values = [ ...

Disabling the visibility of elements through a transparent sticky-top menu

I'm having an issue with my website design. I have a gradient background and a sticky-top menu on the site. The problem is that when I scroll down, the content appears through the menu, which is not ideal. I don't want to apply the same gradient ...

Error: The listen function in React + Redux Simple Router is undefined and cannot be found

I've been attempting to configure react + react-router + redux + redux-simple-router without success. I encounter an issue when adding redux-simple-router, resulting in the error message: "[TypeError: Cannot read property 'listen' of undefi ...

Tutorial on Removing and Re-Adding HTML Elements

Currently, I am utilizing Jquery to temporarily remove an element from the DOM. This specific element consists of an HTML5 video element. However, upon re-adding this element back into the DOM, the video is unable to play and the element appears as blank o ...

What is the best way to display circles (generated from JSON data) in reverse order by incorporating a delay function?

I am currently working on creating an interactive visualization using circles that expand over a specified period, all centered at the same point. I have a script that generates these circles and saves the data in a JSON file. The smallest circle is posit ...

When the onclick function is triggered, two or more characters will be displayed

Functionality: To input name and email, users must click on the virtual keyboard displayed on the screen. Characters entered will be shown in the input box. Implementation: The HTML keyboard interface and associated script have been developed successful ...

Using JavaScript to reduce, group, and sum nested objects

I'm a third-year student working on my first internship project and struggling with organizing and aggregating data from a JSON object. The goal is to group the data by name, calculate total weight per name, and sum up the grades for each entry. I&apo ...

Unleash the power of jQuery by incorporating the Ajax functionality with a hover option to enhance user interactivity. Utilize the .ajax

On my website, I have a calendar displayed with dates like "11/29/2014" stored in an attribute called "data-date". The goal is to check the server for a log file corresponding to that date and change the CSS of the div on mouse hover. Here is the current ...

What is the best way to decrease the border width of a chartjs doughnut chart?

I have a vision for my chart based on the mockup: However, here is what I've been able to achieve using chartjs so far: This is the code I'm working with: datasets: [ { data: [3, 8, 13, 9, 2], backgroun ...

Surprising non-synchronous operation within the computed property "vue/no-async-in-computed-properties" in Vue3

I am currently working on a Vue3 project and encountering an error when running it. Below is the complete code snippet that I am using. Can anyone assist me in resolving this issue? Thank you in advance. <script> import axios from 'axios'; ...

Having difficulty with pagination within a callback function

I have been attempting to paginate in a call to a callback function, but I am encountering an error on the second call. Here is what my function does: let content = '' let size = 100 let from = 1 function result(size, from, callback) { ap ...

What is the best way to combine a hyperlink with a string in an Angular form?

Currently I am in the process of learning angular and experimenting with creating a list of websites that can be clicked on, similar to what you would find in a bookmark app. This is based on a todo example. https://github.com/LightYear9/ToDoList In orde ...

The functionality for tabbed content seems to be malfunctioning on Chrome and Firefox, however it works perfectly

In my index.js file, I have various functions set up like so: // a and b is placed at index.jsp $("#a").click(function (){ //this works on index.jsp and display.jsp(where the servlets forwards it). $("#b").load('servletA.html?action=dis ...

Avoiding accidental clicks on a raycasted object while moving the mouse

I am dealing with a group of clickable objects that can be rotated by using the scroll wheel or by clicking and dragging. The issue I am facing is that when you release the click on top of an object after dragging, it triggers the click animation. Here is ...

Updating and showing a variable in a PHP file using JavaScript within an HTML webpage

My goal is to establish a variable in a PHP file on my server named "likes." Subsequently, I wish to incorporate a like button on my HTML webpage that, when clicked, will utilize JavaScript to modify the "likes" variable in the PHP file and increase it by ...

Animating nested ng-repeat loops

Trying to animate a list of elements divided by rows (the parent ng-repeat) and columns (the child ng-repeat) has been quite challenging. While I was able to achieve the desired animation with individual ng-repeats, the same cannot be said for nested ng- ...

Looking to display parent and child elements from a JSON object using search functionality in JavaScript or Angular

I am trying to display both parent and child from a Nested JSON data structure. Below is a sample of the JSON data: [ { "name": "India", "children": [ { "name": "D ...

Get a document from a NodeJS Server with the help of Express

How can I improve my file downloading functionality in Node.js? Currently, when I try to download a PDF file from the server, the content is displayed as data instead of initiating the download process. I would like it to function similar to how it's ...

Determine the total value of a specific key within a collection of objects

I am grappling with an array of objects: let fileArray = [ { filename: 'File1.txt', bytes: 12345, created: 1548360783511.728 }, { filename: 'File2.txt', bytes: 34567, created: 1548361491237.182 }, { filename: 'File3.txt&apos ...