How can you determine the number of identical objects within an array using Javascript?

Below is a JSON object that stores the ID and type of each object:

let jsonData = [
   {"id": "1", "object": "pen"}, 
   {"id": "4", "object": "bag"}, 
   {"id": "2", "object": "paper"}, 
   {"id": "5", "object": "bottle"},
   {"id": "3", "object": "notepad"}, 
   {"id": "1", "object": "pen"}, 
   {"id": "4", "object": "bag"}, 
   {"id": "3", "object": "notepad"}, 
   {"id": "3", "object": "notepad"}, 
   {"id": "1", "object": "pen"}, 
   {"id": "2", "object": "paper"},
   {"id": "1", "object": "pen"},      
]

I would like to create a new array displaying each object with its corresponding count value in the format below:

|---------------------|------------------|
|        Object       |        Unit      |
|---------------------|------------------|
|         Pen         |         4        |
|---------------------|------------------|
|         Paper       |         2        |
|---------------------|------------------|
|        Notepad      |         3        |
|---------------------|------------------|
|         Bag         |         2        |
|---------------------|------------------|
|        Bottle       |         1        |
|---------------------|------------------|

In essence, the new array will showcase each object along with its respective count. Thank you in advance.

Answer №1

To easily achieve this, you can utilize the Array.reduce method in JavaScript

 let data = [
      {"id": "1", "item": "pen"}, 
      {"id": "4", "item": "bag"}, 
      {"id": "2", "item": "paper"}, 
      {"id": "5", "item": "bottle"},
      {"id": "3", "item": "notepad"}, 
      {"id": "1", "item": "pen"}, 
      {"id": "4", "item": "bag"}, 
      {"id": "3", "item": "notepad"}, 
      {"id": "3", "item": "notepad"}, 
      {"id": "1", "item": "pen"}, 
      {"id": "2", "item": "paper"},
      {"id": "1", "item": "pen"},      
   ];

   let itemSummary = data.reduce( (acc, element) => {

    let objData = acc.find(e => e.item == element.item);

    if (!objData) {
      objData = {item: element.item, count: 0};
      acc.push(objData);
    }

    objData.count = objData.count + 1;
    return acc;
   }, []);
   
   console.log(itemSummary);

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 prevent automatic trimming in EJS variable assignment in Node.js?

When I attempt to write a variable from the database into an EJS table, it is being displayed with default trimming by the EJS template. However, I would like to display the variable from the database without any default trimming. I consulted the EJS temp ...

How can I extract the directory path from a string that includes a file name in Node.js?

Working with multiple files in Node and trying to figure out a way to extract the file name from the directory path without depending on external packages. Is there a built-in solution in Node for this, or do I need to resort to using something like Filena ...

What is the best way to combine a Promise.all with additional Promises?

I need to order the execution of my code as follows: Promise 1 Wait for 1 to finish, then run Promises 2 and 3 simultaneously The final function should wait for Promises 2 and 3 to complete I'm struggling to figure it out, and here is the code I ha ...

Oops! Before proceeding, make sure to call TestBed.initTestEnvironment() first

Currently, I am experimenting with testing a service in Angular. Below is the code snippet I am working on: describe('AddressService', () => { let service: AddressService; let injector: TestBed; let httpTestingController: HttpTesting ...

The callback within an Angular directive is triggered before the model is updated

There is an issue with a directive that has a model and callback mapped to the parent scope. The problem arises when the parent model is updated after the callback has occurred, even though in the code it is assigned before. DEMO: PLUNKER (Click twice or ...

Generating parameters on the fly from an array using jQuery

After implementing a successful plugin on my website, I am now looking to enhance it further by defining state-specific styles dynamically. The current setup allows for passing parameters for specific states, as shown below: $('#map').usmap({ ...

Build error occurred due to the presence of the following error: Module parse failed with an unexpected character ''' (1:0)

I am facing an issue regarding an unexpected character in a node module file. Below is the content of my next.config.js file: /** * @type {import('next').NextConfig} */ const UglifyJsPlugin = require("uglifyjs-webpack-p ...

Does React 16's Portal API serve as a alternative to the Context API?

It appears that the new feature called portals may be able to do a similar job but even better than before. While I am not very familiar with portals, it seems like they could be the latest way to handle updates within nested components. I was aware that ...

The absence of jQuery in Electron script (electron-packager) is causing loading issues

During the process of building and packaging my Electron application using either electron-packager or electron-builder, I encountered a problem where a js file I was loading in my app.js wasn't properly loaded and kept throwing errors. Unfortunately, ...

Building a scrollable dropdown menu with Bootstrap 5: A step-by-step guide

The search for suitable code examples for scrollable dropdown menus compatible with Bootstrap 5 has been challenging. Are there any contemporary methods available to achieve this functionality seamlessly? ...

A step-by-step guide on splitting an element into two separate elements using jquery

I have the following code snippet: <h4>user (role) on 26 Nov 2018 20:39:42 +00:00:</h4> My goal is to transform it into this structure: <h4>user (role)</h4> <p>on 26 Nov 2018 20:39:42 +00:00:</p> The <h4> eleme ...

Is the Angular-fullstack generator production application experiencing issues with serving socket.io correctly?

Having a bit of trouble with two angular-fullstack apps deployed on AWS using the same setup and configuration. It appears that socket.io-client/socket.io.js is not being properly served on one of them, despite both apps having identical settings. There ...

interaction & portal

I am currently managing a website that includes an iframe. Both the main site and the embedded site within the iframe are verifying the $_SESSION["login"]. Therefore, if the session expires, the user will be automatically logged out. The issue I'm fa ...

The simultaneous use of trackball controls and GUI is not compatible

When I click on them, the GUI changes together and I have looked at other answers. However, I am not sure where to put the listener. I tried putting the listener in render(), but it still doesn't work. How can I fix my code? This coding is related to ...

Unable to access and control HTML elements using JavaScript

let button = document.getElementsByTagName('button'); button.value = 8; //button.textCont = 'X'; --- DOESN'T WORK. //button.innerHTML = 'X'; --- DOESN'T WORK. body { ...

How can you dynamically add 'subtext' to a selectpicker in Bootstrap 4?

While working with Bootstrap-4, I am attempting to dynamically add 'data-subtext' next to all the option texts of a selectpicker. The code below successfully creates the list of options from an array, but I am struggling to include the data-subte ...

Steps for updating the homepage to display a personalized welcome message to the user after logging in and redirecting using node.js and

Upon arriving at the homepage, simply click on the sign-in button. Once redirected back to the home page, you will notice a personalized greeting saying 'Welcome [user]'. Wondering how to achieve this? It's as simple as changing the text fro ...

Having trouble with submitting the second stage of a multi-step form through Ajax technology

I'm currently tackling a multi-step form project using JavaScript, specifically focusing on submitting the second step of the form via Ajax. I've taken the initiative to create a distinct JavaScript file titled ajaxRequest.js to manage the Ajax r ...

Adding a child node before an empty node in Chrome with JavaScript Rangy

When attempting to insert a node before an empty element at the start of another element, a problem was noticed. Here is the initial setup: <p>|<span />Some text</p> By using range.insertNode() on a Rangy range to add some text, Chrome ...

Transferring information between Node and Vuejs

I currently have a local Node.js server running on port 3000, and another developer server for front-end using webpack on port 8080. My Node.js server is connected to a MySQL database. The project structure is as follows: SampleProject -> BackEnd - ...