Determine the quantity of particular information within an array of objects

My goal is to calculate the total number of entries based on the color provided by the user. For instance, if the user enters 'red', the program should return 11. I attempted to achieve this but encountered an issue with the variable cnt not being defined after the loop.

let description=[
                {color:'red',qty:6,remarks:'asdf'},
                {color:'green',qty:5,remarks:'asdf'},
                {color:'red',qty:5,remarks:'asdf'},                             
                {color:'yellow',qty:5,remarks:'asdf'},                         
                {color:'blue',qty:5,remarks:'asdf'},                           
                {color:'white',qty:5,remarks:'asdf'}
                ];
{description.map((t,index) =>{
         let cnt=0;
         if(t.color=='red'){
            cnt=cnt+parseInt(t.qty);    
         }
         console.log(cnt);
      }   
      )}
 console.log(cnt);     

Answer №1

The issue in your code lies in the initialization of let cnt=0; within the function, causing it to reset on each iteration and therefore not properly adding up the values.

To resolve this, you can utilize the reduce method to check if the color matches colorToSearch and then accumulate the quantity value accordingly.

let items=[
     {color:'red',qty:6,remarks:'asdf'},
     {color:'green',qty:5,remarks:'asdf'},
     {color:'red',qty:5,remarks:'asdf'},                             
     {color:'yellow',qty:5,remarks:'asdf'},                         
     {color:'blue',qty:5,remarks:'asdf'},                           
     {color:'white',qty:5,remarks:'asdf'}
];

let colorToFind = 'red';

let totalQuantity = items.reduce((acc, val) => val.color === colorToFind ? acc + val.qty : acc, 0)

console.log(totalQuantity);

Answer №2

To simplify the array, first filter it and then use reduce as shown below

let items=[
                {name:'apple',quantity:6,category:'fruit'},
                {name:'banana',quantity:5,category:'fruit'},
                {name:'orange',quantity:5,category:'fruit'},                             
                {name:'carrot',quantity:5,category:'vegetable'},                         
                {name:'potato',quantity:5,category:'vegetable'},                           
                {name:'tomato',quantity:5,category:'vegetable'}
                ];
                
 let totalFruits=items.filter(item => item.category === 'fruit').reduce(function(sum, current) {
                 return sum + (parseInt(current.quantity) || 0);},0)
 console.log(totalFruits);               

Answer №3

To implement the functionality using Array.prototype.reduce(), you can follow this example:

const data=[
  {name:'apple',quantity:6,price:2.5},
  {name:'banana',quantity:4,price:1.5},
  {name:'apple',quantity:8,price:2.5},                             
  {name:'orange',quantity:10,price:1.7},                         
  {name:'pear',quantity:5,price:3.2}                           
];
const fruit = 'apple';
const totalQuantity = data.reduce((accumulator, currentItem) => accumulator + (currentItem.name === fruit ? currentItem.quantity : 0), 0);

console.log(totalQuantity);

Answer №4

The variable ctn is being redefined within each iteration and only exists within the scope of your .map function. This is why you are receiving an error stating "The variable cnt is not defined" after the loop finishes.

To resolve this issue, simply move the declaration of ctn outside of the .map function:

let description=[
                {color:'red',qty:6,remarks:'asdf'},
                {color:'green',qty:5,remarks:'asdf'},
                {color:'red',qty:5,remarks:'asdf'},                             
                {color:'yellow',qty:5,remarks:'asdf'},                         
                {color:'blue',qty:5,remarks:'asdf'},                           
                {color:'white',qty:5,remarks:'asdf'}
                ];
                
let cnt=0;    

description.map((t,index) => {
         if(t.color=='red'){
            cnt=cnt+parseInt(t.qty); //Note: parseInt() isn't needed if qty is always a number
         }
      });
      
 console.log(cnt);

Answer №5

To solve this issue, you can utilize either the array filter or array reduce method. Below is an illustration using the array reduce method.

Within your program, let cnt=0; is placed inside the map function. Consequently, the value of cnt will not be accessible in the second console.log statement.

let information = [{
    color: 'red',
    qty: 6,
    remarks: 'asdf'
  },
  {
    color: 'green',
    qty: 5,
    remarks: 'asdf'
  },
  {
    color: 'red',
    qty: 5,
    remarks: 'asdf'
  },
  {
    color: 'yellow',
    qty: 5,
    remarks: 'asdf'
  },
  {
    color: 'blue',
    qty: 5,
    remarks: 'asdf'
  },
  {
    color: 'white',
    qty: 5,
    remarks: 'asdf'
  }
];

function getTotal(matchedColor) {
  return information.reduce(function(accumulator, current) {
    // Verify if the color matches the supplied parameter
    if (current.color === matchedColor) {
      accumulator += current.qty; // Add to the previous total
    };
    return accumulator;
  }, 0); // The initial value starts at zero for the sum
}
console.log(getTotal('red'));

Answer №6

In my opinion, the use of filter followed by reduce to calculate the total quantity is a more clear and concise approach.

let items = [
  {name:'apple',quantity:10},
  {name:'banana',quantity:15},
  {name:'orange',quantity:20},                             
  {name:'kiwi',quantity:12},                         
  {name:'pear',quantity:8},                           
];
let totalQuantity = items.filter(item => item.name !== 'banana').reduce((prev, {quantity}) => prev + quantity, 0);
console.log(totalQuantity);

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

Determine the sum of all the values entered into the text fields

On my ASP.Net page, there is a screen where users can select between 1 and 5 text boxes to input an amount. Depending on certain criteria, a specific number of these edit boxes are displayed - no hiding involved. So if I choose to display 3 boxes, only 3 w ...

Getting started with TypeScript in combination with Node.js, Express, and MongoDB

I'm a beginner in working with TypeScript, Node.js, Express, and MongoDB. I need guidance on the end-to-end flow for these technologies. Can someone please suggest steps or provide links for a step-by-step process? What is the procedure to compile/r ...

How can one eliminate the white space surrounding the data that Vue is binding?

Working with Vue, I've noticed a gap on the screen following the data binding. Instead of using Vanilla JavaScript's trim() function, is there a way to remove leading and trailing whitespace? Let me provide you with the code for the data binding ...

Show the array in a JFrame

Seeking guidance on displaying a list of arrays stored in my main class within a JFrame contentpane created in another class. While I understand the fundamentals of creating a JFrame and contentpane, I'm unsure how to effectively pass the array into t ...

Could someone please guide me on how to use JQuery to set a radio button as checked?

<input type="radio" name="sort" value="2" id="myradio"> Is there a way to set this as the selected option using JQUERY? ...

Can next.js rewrites be configured with environment variables?

Currently, I am in the process of developing my application with a next.js frontend and express.js backend. During development, I simply run the relevant dev servers in the terminal. However, now I am looking to deploy my app using Docker for production. I ...

Problem Encountered with Navigation Bar following the Cloning and File Transfer in a React (Next) Project

I cloned the repository and transferred the files using these commands: 1. git clone https://github.com/adrianhajdin/portfolio.git 2. cd portfolio 3. mv * .. Upon executing npm run dev, everything appears fine, but upon clicking on the About button or ...

How can you efficiently load the materials for a THREE.BoxGeometry using THREE.LoadingManager()?

I am looking to enhance the image quality of a geometry after user interaction by initially loading low-resolution assets and then switching to high-resolution assets when the user interacts with it. When using the following standard code: var materials = ...

Converting Excel sheets to JSON using Vue.js

Struggling with reading excel files in vue.js as the memory usage spikes to 5GB after processing a small file. Need help converting the file to JSON format. Tried various options mentioned in the documentation but encountered different errors. Also checked ...

Executing a JavaScript code in a Python webdriver: A step-by-step guide

Using Selenium 2 Python webdriver: I encountered an issue where I needed to click on a hidden element due to a hover effect. In search of solutions to unhide and select the element, I came across the following examples: Example in Java: JavascriptExecut ...

What is causing my function to not wait for the resolution of the Promise?

checkout.ts updateGlobalValue(){ updateShadowDomButton(); let globalValue = fetchGlobalValue() } web_component_render.ts let globalValue; async fetchData() { let booleanFromApi = await callToExternalAPI(); return booleanFromApi; } functi ...

Is it possible to insert a second hyperlink into a JavaScript-occupied anchor?

Check out my reference page at: To change the content in a 'containerarea' div, I am utilizing Dynamic Drive's "Dynamic Ajax" script. Below is an example of the anchor code used: <a href="javascript:ajaxpage('videos-maintenance/app ...

React JS for loop not displaying any output

I am trying to create a component that loops from 0 to the value entered as a prop. if (props.number !== "" && props.toPow !== "") { for (let i = 0; i < props.toPow; i++) { return ( <div> & ...

Three.js brings life to reflections through dynamic rendering

Embarking on my coding journey with JavaScript and exploring Three.js I created an experiment using shaders and an environment map (http://jsfiddle.net/gnazoa/3hxrky6k/1/) Through a tutorial on the Three.js website, I discovered how to achieve reflection ...

Consideration of tiebreakers in the longest word array

function findLongestOfThreeWords(word1, word2, word3) { word1 = word1.split(' '); word2 = word2.split(' '); word3 = word3.split(' '); var newArr = word1.concat(word2,word3); var longestWord = []; var longestWor ...

Tips for adjusting the ion-select popup height in Ionic

I've been attempting to customize the max-height property of a div that organizes elements in a popup using the interfaceOptions attribute in Ionic, but so far I haven't been successful. Here's what I have tried: cu ...

Enhancing wordpress custom fields using ajax without overwriting them

Seeking assistance with updating a custom field in WordPress. I have a gallery of images with textareas for comments attached to each image. Currently, I can enter text into a textarea and save it instantly using AJAX to the database. However, when I add a ...

The scrolling speed of my news div is currently slow, and I am looking to increase its

This is the news div with bottom to top scrolling, but it is slow to start scrolling. I want to increase the speed. The current behavior is the div appears from the y-axis of the system, but I want it to start exactly where I define. The scrolling div is ...

Steps for filling an HTML table within a dynamically loaded DIV

I have a container in my HTML page where I dynamically load other pages using the jQuery.load() function. One of the pages requires me to populate a table from the database just after/before it loads. How can I trigger a JavaScript function to execute righ ...

Failure to Fetch the Uploaded File's Value Using the Parameter

Objective: My aim is to automatically upload the second input named "file2" to the action result using jQuery code that is compatible with the latest versions of Firefox, Chrome, and Internet Explorer. Issue: The problem arises when HttpPostedFileBase ...