Count the occurrences of values in a JSON object using JavaScript

I'm dealing with a JSON array in vanilla JavaScript (no JQuery) and I've hit a roadblock.

My task is to identify each unique value for 'Service' and calculate the frequency of each value.

For example, if the value 100 appears 3 times and the value 101 appears 5 times, the desired result should look like:

{ "100" : "3", "101" : "5"}

I'd prefer not to resort to a traditional loop if there's a more succinct solution available such as using forEach()

Answer №1

To start, you should first transform your JSON array into an object array:

let json_arr = '[200, 201, 200, 202, 201]';
let objArr = JSON.parse(json_arr);

After that, it's a matter of counting, which will vary depending on the elements in your array. If they are numbers, you can use a simple approach like this:

let counts = {};
objArr.forEach(function(item) {
    counts[item] = counts[item] ? counts[item] + 1 : 1;
});

This will give you

counts = {'200': 2, '201': 2, '202': 1}
.

Answer №2

Don't feel obligated to use

<array>.forEach(<callback>)
, as an alternative you can opt for a traditional for..of loop:

let output = {};
for (let value of data) output[value] = output[value] ? output[value] + 1 : 1;

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

Conflicts in SwiperJS Timeline Management

Having a Timeline on my Website using SwiperJS presents challenges with conflicting functions. The goal is to navigate swiper-slides by clicking on timespans in the timeline. The desired functionality for the timeline includes: Sliding to the correspondi ...

Using JavaScript to sort data within specific timeframes

How can I extract data based on timestamps greater than 06? "use strict" const data = [ {timestamp: "2020-04-23 05:05", totalAvg: 2.596211180124224}, {timestamp: "2020-04-23 05:10", totalAvg: 3.22052273203436}, {timestamp: "2020-04-23 05:15", t ...

Node.js application - varying NODE_ENV upon NPM launch

Operating my node.js application can be quite confusing. When launched by npm start, it operates in "production" mode, whereas when launched using node start.js, it runs in 'development' mode. I want to ensure that the 'development' mo ...

"Problem with the Hide/Show Load feature: it's not functioning

After a user submits a form, my script shows 2 divs and hides 1 div. The form's target is an Iframe on the same page. I am looking to delay the Hide/Show events until the Iframe loads. I was successful in accomplishing this with a loading animation, ...

The Angular carousel fails to display or operate properly

I am encountering an issue where the content is not displaying when using the angular-carousel directives: <ul rn-carousel rn-carousel-controls rn-carousel-index="carouselIndex" rn-carousel-buffered > <li ng-repeat="slide in slides track by ...

The constructor of App\Events\ChatEvent requires its first argument ($data) to be an array, but a string was provided instead

This is the Event: public $data = []; public function __construct(array $data) { $this->data = $data; } Once a value is passed to the event: public function saveMessage(Request $request) { $messageData = [ "to_user_id" =& ...

Transforming a large JSON dataset into a CSV format

Seeking help with converting a massive JSON file containing tweet data (48MB) to CSV format for importing into a SQL database and cleansing purposes. Despite attempting multiple JSON to CSV converters, they all error due to the file size. Is there an effi ...

What is the best way to send multiple arrays of JSON objects to a Stimulsoft report using JavaScript?

I am currently working with this JavaScript code snippet: var viewer = new window.Stimulsoft.Viewer.StiViewer( null, "StiViewer", false ); var report = new window.Stimulsoft.Report.StiReport(); const { data: reportData } = await GetRequest ...

Do I need to include success as a parameter in my Ajax call even if my function does not return any values?

When an image is clicked, I trigger an ajax call. The image includes an href tag that opens a different page in a new tab upon click. The purpose of this ajax call is to record the user's clicks on the image for telemetry purposes in a database table. ...

What other methods are available to verify null and assign a value?

Is there a more efficient approach for accomplishing this task? theTitle = responsesToUse[i]["Title"]; if(theTitle == null) theTitle = ""; ...

Is there a way to use Jquery to determine if a parent div contains a scroll

I'm trying to find a jQuery example that checks if any parent div has a scroll bar, but I can't seem to locate a helpful one. Here is the code snippet I am working with: <div> <div class="heading"> <div class="visit ...

Transform a CSV file into a JSON format using Python

I am having a successful conversion of my code. However, I encountered an issue when trying to import the JSON file into Firebase as it stated that the files are invalid. import csv import json csvfile = open('C:/Users/Senior/seaborn-data/Denver Dat ...

What can be done to address the issue of v-model select option onchange displaying the previously selected value or becoming stuck on a static value rather than updating

Whenever I navigate to the message page and select a device, the v-model selected value changes. However, if I go to the device or contact page, the v-model selected value remains unchanged or goes back to the last selected value. Below is the function in ...

Having trouble with Django's submit POST method for creating objects

Latest Updates: I have successfully implemented a feature where the page does not reload upon clicking the submit button. To achieve this, I filled out the form and inspected the page source code. The form structure was as follows: https://i.sstatic.net/ ...

Google Charts is unable to display any data because the table does not contain

After browsing numerous forums and attempting various solutions, I encountered a new challenge each time. My goal is to generate a Google line chart using data from a MYSQL table and encoding it in JSON. Then, I aim to utilize an HTML file to showcase the ...

AngularJS array value with HTML tags is not displaying properly upon invocation

In Angular, I have an array that has the following structure: $scope.posts = [ { "ID" : id(), "Title" : "A", "Company" : "Company A", "Location" : "San Francisco, CA", "Date" : "2016-06-20", "Description ...

Display a pop-up window upon clicking anywhere on the webpage using jQuery and HTML

Is it possible for me to create a pop-up window that opens a specific website when a user clicks anywhere on the page, similar to pop-up companies? Can this be achieved using HTML, JavaScript, and jQuery? Any help would be greatly appreciated. ...

Firefox is unable to display SWF files

My code snippet: <div id="sw" style="cursor:pointer" > <object id="swfobj" type="application/x-shockwave-flash"> </object> The JavaScript part: function openfile(filePath) { $("#swfobj").attr("data", filePath); $("#sw ...

To concatenate an array into a single line, you can use the JSON.stringify() method

Could someone help me with using JSON.stringify to keep my data on the same line in an array? I am aiming for a format like this: "alice": { "college": "Stanford", "favorite_color": "purple", "favorite_numbers": [7, 15] }, "dave": { "college": "H ...

Getting a result from a Node.js function that includes a database query

Currently, I am diving into the world of Node.js and delving into working with MySQL connections. There is a particular function that should retrieve a set of rows from the database successfully. However, after retrieving these rows, I am unsure of how to ...