What is the total count of different types of objects present in the array?

...
let stock = [
  { candy: "Twix", available: 150, weeklyAverage: 200 },
  { candy: "Kit Kat", available: 80, weeklyAverage: 100 },
  { candy: "Skittles", available: 250, weeklyAverage: 170 },
  { candy: "Reese's Pieces", available: 120, weeklyAverage: 40 }
];

// create a function named countCandyVarieties
function countCandyVarieties(stock) {
}
...

I am having trouble figuring out how to iterate through the stock array and determine the total number of candy varieties. The candies in stock include Twix, Kit Kat, Skittles, and Reese's Pieces, totaling 4 varieties. Can someone please assist me in writing the function that should return the final count?

Answer №1

It seems you're interested in calculating the total quantity of candies available.

let candyStock = [{
    name: "Hershey's Kisses",
    quantity: 500,
    weeklySales: 100
  },
  {
    name: "Skittles",
    quantity: 300,
    weeklySales: 150
  },
  {
    name: "Reese's Cups",
    quantity: 400,
    weeklySales: 120
  },
  {
    name: "M&M's",
    quantity: 600,
    weeklySales: 200
  }
];


// Define the calculateTotalCandies function here
function calculateTotalCandies(candyStock) {
  let total = candyStock.reduce((acc, item) => {
    acc += item.quantity;
    return acc;
  }, 0)
  console.log(total)
}

calculateTotalCandies(candyStock);

Answer №2

If you are unsure about what exactly you are trying to tally up. In case you are only interested in counting the variety of candies and each item in the list represents a different type of candy, you can use this function:

function countCandyTypes(inventory) {
  return inventory.length;
}

However, if there could be duplicates of the same type of candy within the list, then you can use this function:

function countCandyTypes(inventory) {
  var types = [];
  for (const record of inventory) {
    if (!types.includes(record.candy)) {
      types.push(record.candy);
    }
  }
  return types.length;
}

Alternatively, if you are simply interested in the total number of candies regardless of the type:

function countCandyTypes(inventory) {
  var count = 0;
  for (const record of inventory) {
    count += record.inStock;
  }
  return 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

Two components, one scroll bar, both moving within the same plane

For those interested, here is the JSFiddle link for further exploration: https://jsfiddle.net/q6q499ew/ Currently, there is a basic functionality in place where when you scroll past a certain point, an element becomes stuck until you start scrolling back ...

What is the best way to immediately update the state in a React functional component?

Having recently started learning React, I find myself struggling to understand the lifecycle of a functional component. Let's consider a scenario where I have multiple checkboxes labeled as: checkbox, a, b, c, and d, each corresponding to values a, b, ...

Initiating an AJAX request to a JSP file

Attempting to make an ajax call to a jsp page as shown below: $(document).ready(function () { $('#photo').photobooth().on("image", function (event, dataUrl) { alert(dataUrl); //alert($('#mygroupuserid')); ...

Bot on Discord using Discord.Js that generates unique invites for users

I'm trying to find a way to generate an invite link for users to keep track of invites. The code I have currently is creating the invite for the Bot instead. const channel = client.channels.cache.find(channel => channel.id === config.server.channel ...

Hover over or click to automatically focus on the input field

I have an icon that triggers focus on an input field when hovered over. I also want the same functionality to occur when the user clicks on the icon. if(!mobile){ $('#search-icon').hover( function(){ if($('.sear ...

Incorporating additional information into the database

When I run the code, I see a table and a button. After entering data in the prompts as instructed, the table does not get updated. I'm unsure why this is happening. Can someone please explain? <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Trans ...

Decoding the file's encoding: A beginner's guide

I need help determining the encoding of a file in order to only upload CSV files with utf-8 format. If there are any non utf-8 characters, I want to display an error message. Currently, I am utilizing Papa Parser for parsing. Is there a way to detect the ...

Issue with Refresh Triggering Update, localStorage, useState, useEffect Combination

I want my app to execute the code inside the useEffect hook every 5 seconds, regardless of whether the page is refreshed or not. Currently, the code only runs when the page is refreshed and then remains inactive until the page is refreshed again. It seems ...

Storing the current date() in JSON format using AngularJS

I am currently working on saving various data, including the current date, in a JSON file stored in LocalStorage. While I have been successful in saving the data, the date is saved in the ISO 8601 format: [{"date":"2014-10-13T17:55:32.953Z"}] This format ...

What are some methods to conceal an email address using Javascript?

let user = 'alex'; let domain = 'gmail.com'; let send = 'msg'; document.getElementById("email").href = "ma" + send + "ilto:" + user + "@" + domain; <a id="email"> <img src="imgs/pic.jpg"> </a> I have been w ...

Having trouble getting Ajax to function properly with CodeIgniter

Here is the AJAX code snippet: $.ajax({ url: '<?php echo base_url(); ?>deleteRowUsingApiKey/index', //This is the current doc type: "POST", //dataType:'json', // add json datatype to get json data: {name ...

Automatically calculate line total using jQuery when input blurs

Within my interface, I have a section that allows users to input their class information for reimbursement. There are 6 line items available for them to fill out with the cost of books and tuition. Ideally, I would like the user to be able to enter these c ...

Adding a class to an img tag with TinyMCE

Currently, I am utilizing the TinyMCE editor as a standalone editor in my content management system (CMS). Within the CMS, there is an automatic setting that adds a curved border to any image tags within the cms div ID. In certain cases, I require the op ...

Tips for customizing the appearance of a redux-tooltip

After implementing the redux-tooltip from this GitHub repository, I wanted to customize its styling to better align with my application's design. However, I realized that the Tooltip-Component's divs do not have any identifiers or class names, ma ...

Creating dual permission menus for two different roles in Vue JS 3

This is my router file checking which role is logged in: router.beforeEach((to, from, next) => { if (to.matched.some(record => record.meta.requiresAdmin)) { if(VueJwtDecode.decode(localStorage.getItem('accessToken')).sub == &quo ...

Encountering difficulty locating the $wpdb variable during an AJAX request

I am currently developing a PHP application for WordPress and facing a challenge in retrieving a value from a database using AJAX every 2 seconds. I have created a new function in a separate file to handle this task. <?php global $wpdb; function retrie ...

How can I merge my two custom filters into a single, more efficient custom filter?

I have developed two custom filters that are quite similar. The only distinction between these filters is the array they utilize. Therefore, I am considering creating a single custom filter and passing an array as a parameter to it. The arrays I intend to ...

I'm working on an Angular2 project and I'm looking for a way to concatenate all my JavaScript files that were created from TypeScript in Gulp and then include them in my index

How can I concatenate all JavaScript files generated from typescript in my Angular2 project with Gulp, and then add them to my index.html file? I am using Angular2, typescript, and gulp, but currently, I am not concatenating the javascript files it genera ...

When using Node.js, the process.exit() function will not terminate if there is an open createReadStream

My program interacts with Asterisk using EAGI, where Asterisk communicates with my Node.js application by sending data via STDIN and receiving commands via STDOUT. When a user ends the call, the Node.js process receives a SIGHUP signal for clean terminatio ...

Show the response obtained after making a POST request

In my current project, I am utilizing vanilla JavaScript to send a POST request to my Flask App. I have implemented a validation feature that checks for duplicate usernames when a user is signing up. If the username already exists, a 406 status response is ...