Determining the number of occurrences of a particular variable in a JSON-indexed object using JavaScript

Seeking some guidance as I navigate through unlabelled data for the first time. The challenge lies in determining the total count of department_count from the JSON object below.

No matter how many solutions I try or logic I implement, I keep running into roadblocks and failing to retrieve the desired output.

With a total of 3 departments, the expected result should be 3. An alternative approach is to calculate the sum of department_count in each iteration.

THE DESIRED RESULT IS 3

var myObject =[
{
  "school_id":"1",
  "school_name":"XYZ",
  "department_count":1,
  "department":[
     {
        "id":"stu1",
        "name":"sammy",
        "height":88,
        "weight":2,
        "bmi":1,
        "type":"Healthy"
     }
  ]
},
{
  "school_id":"2",
  "school_name":"ABC",
  "department_count":2,
  "department":[
     {
        "id":"stu2",
        "name":"Sam",
        "height":5,
        "weight":2,
        "bmi":1,
        "type":"Skinny"
     },
     {
        "id":"stu3",
        "name":"REd",
        "height":0,
        "weight":0,
        "bmi":0,
        "type":""
     }
   ]
}
]

Answer №1

Perhaps this solution could be of use to you.

var myObject =[
   {
      "school_id":"1",
      "school_name":"XYZ",
      "department_count":1,
      "department":[
         {
            "id":"stu1",
            "name":"sammy",
            "height":88,
            "weight":2,
            "bmi":1,
            "type":"Healthy"
         }
      ]
   },
   {
      "school_id":"2",
      "school_name":"ABC",
      "department_count":2,
      "department":[
         {
            "id":"stu2",
            "name":"Sam",
            "height":5,
            "weight":2,
            "bmi":1,
            "type":"Skinny"
         },
         {
            "id":"stu3",
            "name":"REd",
            "height":0,
            "weight":0,
            "bmi":0,
            "type":""
         }
      ]
   }
]

let total = 0
for (let i = 0; i < myObject.length; i++) { 
  total += myObject[i].department_count
}

console.log(total);

Answer №2

To achieve this, all you need is a handy sumBy function. I also suggest checking out the following resource: 30 seconds of code. You'll definitely gain more insights from it.

const sumBy = (arr, fn) =>
  arr
    .map(typeof fn === 'function' ? fn : val => val[fn])
    .reduce((acc, val) => acc + val, 0);

var myObject =[
{
  "school_id":"1",
  "school_name":"XYZ",
  "department_count":1,
  "department":[
     {
        "id":"stu1",
        "name":"sammy",
        "height":88,
        "weight":2,
        "bmi":1,
        "type":"Healthy"
     }
  ]
},
{
  "school_id":"2",
  "school_name":"ABC",
  "department_count":2,
  "department":[
     {
        "id":"stu2",
        "name":"Sam",
        "height":5,
        "weight":2,
        "bmi":1,
        "type":"Skinny"
     },
     {
        "id":"stu3",
        "name":"REd",
        "height":0,
        "weight":0,
        "bmi":0,
        "type":""
     }
   ]
}
];

var results = sumBy(myObject, x => x.department_count);
console.log(results);

Answer №3

When the department_count value has been established, you can simply retrieve the total number of objects in the array as totalDepartments without needing to iterate through it

let totalDepartments = myObject.length

Answer №4

A unique counter with duplicate check

const schoolsData =[
{
  "school_id":"1",
  "school_name":"XYZ",
  "department_count":1,
  "department":[
     {
        "id":"stu1",
        "name":"sammy",
        "height":88,
        "weight":2,
        "bmi":1,
        "type":"Healthy"
     }
  ]
},
{
  "school_id":"2",
  "school_name":"ABC",
  "department_count":2,
  "department":[
     {
        "id":"stu2",
        "name":"Sam",
        "height":5,
        "weight":2,
        "bmi":1,
        "type":"Skinny"
     },
     {
        "id":"stu3",
        "name":"REd",
        "height":0,
        "weight":0,
        "bmi":0,
        "type":""
     }
   ]
}
]
var uniqueSchoolNames=[]
var count=0;
schoolsData.forEach(school=>{
if(!uniqueSchoolNames.includes(school.school_name))
{ uniqueSchoolNames.push(school.school_name);count++;
}})
console.log(count);

Answer №5

To accomplish this task, you can utilize the Array.prototype.reduce() method:

const students = [{school_id: '1', school_name: 'XYZ', department_count: 1, department: [{id: 'stu1', name: 'Sammy', height: 88, weight: 2, bmi: 1, type: 'Healthy'},]}, {school_id: '2', school_name: 'ABC', department_count: 2, department: [{id: 'stu2', name: 'Sam', height: 5, weight: 2, bmi: 1, type: 'Skinny'}, {id: 'stu3', name: 'Red', height: 0, weight: 0, bmi: 0, type: ''}]}];

const totalDepartments = students.reduce((acc, { department_count }) => acc + department_count, 0);

console.log(totalDepartments);

Answer №6

There are numerous techniques available, but what you really need is a method that involves looping.

One approach is to utilize the Array.reduce function.

const myObject = [{"school_id":"1","school_name":"XYZ","department_count":1,"department":[{"id":"stu1","name":"sammy","height":88,"weight":2,"bmi":1,"type":"Healthy"}]},{"school_id":"2","school_name":"ABC","department_count":2,"department":[{"id":"stu2","name":"Sam","height":5,"weight":2,"bmi":1,"type":"Skinny"},{"id":"stu3","name":"REd","height":0,"weight":0,"bmi":0,"type":""}]}];
const sum = myObject.reduce((acc, curr) => {
  acc += curr.department_count;
  return acc;
}, 0);
console.log(sum);

Edit: You could also use Object destructuring to improve readability of the code.

const myObject = [{"school_id":"1","school_name":"XYZ","department_count":1,"department":[{"id":"stu1","name":"sammy","height":88,"weight":2,"bmi":1,"type":"Healthy"}]},{"school_id":"2","school_name":"ABC","department_count":2,"department":[{"id":"stu2","name":"Sam","height":5,"weight":2,"bmi":1,"type":"Skinny"},{"id":"stu3","name":"REd","height":0,"weight":0,"bmi":0,"type":""}]}];
const sum = myObject.reduce((acc, {department_count}) => acc + department_count, 0);
console.log(sum);

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

"Downloading an image from an encoded base64 canvas triggers an error due to exceeding the maxUrlLength

I'm using javascript to create a canvas drawing on my webpage and then convert it into a base64 image format. After that, I encode the URL of the image to obtain an encoded URL. I came across a post where it was mentioned that using window.location.hr ...

Slider for jQuery or Ajax framework

Currently, I am in search of a gauge that contains multiple concentric circles, with each circle displaying values of different entities, similar to the image provided. Each individual needle indicates the value of its corresponding entity. I have come a ...

Performing correlation calculations using complex for loops in MATLAB

The code I currently have is functional up to the point of ------ separation. Beyond that, Matlab does not return any errors, but it also does not provide values for bestDx or bestDy. Assistance with this issue would be greatly appreciated. (The precedin ...

"Attempt to create angular fork results in an unsuccessful build

I have recently created a fork of angularJs and I am facing an issue when trying to build it. The build process fails when running grunt package npm -v --> 3.5.2 bower --version --> 1.7.2 I followed the steps provided in the official documentation ...

Obtaining a file from the Firebase database

After successfully implementing the login functionality in my app, I am now attempting to retrieve the user's document in order to display their name on the page. email = loginemail.value; password = loginpassword.value; signInWithEmailAndPass ...

Error encountered when attempting to retrieve posts using Axios: Unexpected symbol detected, expected a comma (25:4)

I've been working on implementing an axios getPosts function, but I keep encountering a syntax error that I can't seem to locate in my code. getPosts = async () => { let data = await api.get('/').then(({ data }) => data); ...

Implementing a redirect and setting a background image dynamically in ASP.NET using code-behind

I have a section in my PHP template with a onclick event handler. My goal is to redirect users to another page when they click on this section. Here's what I've attempted: HTML: <section id="header" onclick="window.location.href='Anoth ...

Strategies for sending data to child components in Vue

Within my parent component, I am making an API call and receiving a response. My goal is to pass this response as a prop to a child component in Vue. Below is the snippet of the parent component and the API call: <button class="btn button col-2&quo ...

Exploitable Weakness Found in NestJS Version 8.4.5

After running npm audit on my npm package recently, I encountered an error that is related to the dicer package, widely used by NestJS. I have looked for solutions online but haven't been able to find any fixes so far. Has anyone else managed to reso ...

What is the top choice for creating a shallow copy of an array

While delving into the vue source code today, I stumbled upon a method of writing that left me puzzled. view source const deduped = [...new Set(pendingPostFlushCbs)] My initial thought is that it is a shallow copy of the array. But why is there a need t ...

Mastering the Art of Binding Option Data from API Responses in Vue.js

Just starting out with Vue.js and attempting to bind option data from an API response. I've made an axios call in the mounted() hook and assigned the companies data from the response, but I'm encountering errors as shown below. 373:11 error ...

Guide to streaming audio files using vue.js

I am attempting to incorporate an audio file into my vue.js project using the following code: import sound from '../../recordings/sound.mp4' const audio = new Audio(sound) audio.play() Although this method works perfectly fine, I have encounter ...

Using the strtok function to separate a set of strings into individual characters in C

This is a follow-up to my previous inquiry. After successfully capturing and storing user input as strings, I managed to transform this: 1:E 2:B 2:B 2:B 4:G Into this: 1:E 2:B 2:B 2:B 4:G Creating an array of strings. The next step that isn't fu ...

In a set of numbers, one specific number is repeated n/2 times while the remaining n/2 numbers are all different from each other

Given an array of n numbers where one number is repeated n/2 times and the other n/2 numbers are distinct. The task is to find the repeated number with a solution complexity of O(n) using exactly n/2+1 comparisons. The challenge lies in achieving n/2+1 co ...

Printing a Page Using Angular 5

Is there a way to print a specific section of my website with Angular 5? I've searched online for a solution, but it seems like most options are tailored for Angular. Any advice? ...

Save information in a session using html and javascript

I'm having trouble accessing a session variable in my javascript code. I attempted to retrieve it directly but ran into issues. As an alternative, I tried storing the value in a hidden HTML input element, but I am unsure of how to properly do that wit ...

Excessive image display | HTML and CSS synergize

I am having some trouble with my image gallery. Each image is displayed as a vertical column and has zooming effects when hovered over. Clicking on an image should show it in full screen with a caption. The problem arises when dealing with images that are ...

Concentrate on the HTML element once it becomes active

I am facing a challenge where I need to focus on a specific input element. However, there is a spinner that appears on page load and remains hidden until certain http requests are completed. All inputs are disabled until the requests are finished. The setu ...

Stop Carousel when hovering over individual items (Owl Beta 2)

After creating a unique navigation that is separate from the carousel, I encountered some issues with the autoplay feature. Below is the HTML markup: <div class="carousel"> <div class=""> <img src="assets/img/carousel1.jpg" /&g ...

Issues with rendering Google Maps on google-maps-react persists, stuck endlessly in loading phase

After following the tutorial for google-maps-react, I attempted to display a Google Map in my app using the same structure as the example. However, the map is not rendering. Link to Tutorial There are no errors showing up in my console. Here is the dire ...