Calculate the worth of a specific item within an array of objects and save the outcome as a new attribute

I am attempting to calculate the value in each element and then create a new element called "Count". Rule: Count the quantity if the next element has the same "Quantity" value, then add the total to a new element named "Count". I have tried implementing this using a for loop function, but unfortunately, my code did not work as expected.

Here is the data I am working with:

let myData = [
                {
                    Name: 'Section 1', 
                    Details:[
                        { Product: 'Ballpen', Quantity: 120},
                        { Product: 'Pencil', Quantity: 120},
                        { Product: 'Marker', Quantity: 80},
                        { Product: 'Highlighter', Quantity: 120}
                    ]
                },
                {
                    Name: 'Section 2', 
                    Details:[
                        { Product: 'Paper', Quantity: 40},
                        { Product: 'Bond Paper', Quantity: 75},
                        { Product: 'Colored Paper', Quantity: 75},
                        { Product: 'Oslo paper', Quantity: 40}
                    ],
                }
            ]

Expected Result: The table will look like this...


  • PRODUCT * Quantity * Count *

  • Ballpen * 120 * 2 *
  • Pencil * 120 * 2 *
  • Marker * 80 * 1 *
  • Highlighter * 120 * 1 *

This means that it will count every time the quantity of a product matches the quantity of the next element. The counting stops even if there are other elements with the same value, but they are not consecutive.

※ On the Console.log(). It will appear as...

Section 1 : {
                [ Product = 'Ballpen', Quantity = 120 , Count = 2],
                [ Product = 'Pencil', Quantity = 120 , Count = 2],
                [ Product = 'Marker', Quantity = 80 , Count = 1],
                [ Product = 'Highlighter', Quantity = 120 , Count = 1],
            },
Section 2 : {
                [ Product = 'Paper', Quantity = 40 , Count = 1],
                [ Product = 'Bond Paper', Quantity = 75 , Count = 2],
                [ Product = 'Colored Paper', Quantity = 75 , Count = 2],
                [ Product = 'Oslo paper', Quantity = 40 , Count = 1],
            },
//Other codes here...

I apologize for any confusion, as I am still learning how to manipulate data. Thank you for your patience and understanding. :)

Answer №1

I trust this meets your requirements

let myData = [
                {
                    Name: 'Department A', 
                    Details:[
                        { Item: 'Desk', Quantity: 10},
                        { Item: 'Chair', Quantity: 15},
                        { Item: 'Lamp', Quantity: 5},
                        { Item: 'Shelf', Quantity: 12},
                    ]
                },
                {
                    Name: 'Department B', 
                    Details:[
                        { Item: 'Computer', Quantity: 20},
                        { Item: 'Keyboard', Quantity: 25},
                        { Item: 'Mouse', Quantity: 30},
                        { Item: 'Monitor', Quantity: 10}
                    ],
                }
            ]
            myData.forEach((ele, idx)=>{
                ele.Details.forEach((ele2, idx2)=>{
                    let value = ele2.Quantity;
                    let count = 0;
                    let sliced = ele.Details.slice(idx2, ele.Details.length)
                    let ok = true;
                    sliced.forEach(ele3=>{
                        if (ele3.Quantity == value && ok)
                            count++;
                        else
                            ok = false
                    })

                    ele2.Count = count;
                    if(typeof ele.Details[idx2 - 1] != 'undefined')
                    {
                        if (ele.Details[idx2].Quantity == ele.Details[idx2 - 1].Quantity)
                            ele.Details[idx2].Count = ele.Details[idx2 - 1].Count
                    }
                    
                })
            })
            console.log(myData);

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

The empty string is not getting recognized as part of an array

Currently, I have a textarea field where pressing enter submits and creates a new item in the array. Pressing shift + enter creates a new line in the textarea input field. But when trying to submit by pressing shift and enter after creating a new line, it ...

Having trouble with Vue image source file paths?

Having an issue with loading an image via file_path on Vue. When using a hardcoded path, it works fine. Refer to the sample code below: JavaScript function getRestaurantsbyId(id) { var restaurants = { "1" : { "name": "xxxx", ...

Angular nested lists with drag and drop functionality

Recently, I've been working on creating a drag and drop dashboard and stumbled upon an amazing nested list at this link. This particular implementation uses the AngularJs JavaScript framework. However, since I don't have much experience with it, ...

The Cloudinary Nuxt Module is throwing an error: "Unexpected element cld-image"

Currently, I have integrated the @NuxtJS/Cloudinary module in my application as follows: <cld-image :public-id="post.photoURL" class="rounded-circle me-1" type="fetch ...

Utilize Express.js to load a random HTML page

Hey there, it's Nimit! I could really use some assistance with my code. I'm trying to figure out if it's possible to load different HTML pages on the same URL like www.xyz.com/home/random. Can more than one HTML page be randomly loaded? I ...

Enhance your Vue app with filtered categories using Vue-google-chart

What is the process for creating a filter category in a bar chart using the vue-google-charts wrapper in Vue.js? I have successfully created a stacked bar chart and now I am looking to add a filter by label inside the legend. Here is my vue application: ...

Having difficulty managing asynchronous functions with the useState hook in React

import React from "react"; import { UserContext } from "./../contexts"; import { removeStoredAuthData, storedAuthIsValid, storeNewAuthData, } from "./../utils/auth"; import { getUserInfos } from "./../api/userAuthen ...

Utilizing Google Geochart for displaying multiple data values within the same country from JSON dataset

I am facing an issue where only the last row is being displayed in a Google Geochart for each country, despite trying to fetch data from my database via JSON. The problem is that only 'Supplier 2' is showing up, as highlighted below. I have gone ...

Despite successfully passing props into V-for, the output does not display the props as expected

I've been attempting to accomplish a straightforward task, but for some reason, it's not working and I can't figure out why. Within the parent component, App.vue, I have the following: data() { return { servers: [ { ...

Leveraging previous state values within a setInterval function in React

Could someone please provide me with an answer to this topic? When I attempt to implement the Interval in the correct way (including cleanup), I encounter the following code: const [count,setCount] = useState(0) useEffect(() => { const interval = ...

The application encountered an exception and has ceased to respond, displaying a custom error page

I have a .NET application running on IIS 7 that is accessed from IE7. When a specific exception occurs, the page is redirected to a plain .htm page with a back button that should take the user back to the previous page. This exception handling is implement ...

Having trouble linking a sqlite file in your tauri + vue project?

After successfully installing tauri-plugin-sql by adding the specified content to src-tauri/Cargo.toml : [dependencies.tauri-plugin-sql] git = "https://github.com/tauri-apps/plugins-workspace" branch = "v1" features = ["sqlite" ...

Using Angular to fetch API response and convert it into a promise

I've been following the Angular tutorial available at https://angular.io/tutorial/toh-pt6. The tutorial demonstrates how to retrieve a Json response from an API call and then match it to a promise. One specific example from the tutorial is as follows ...

"Encountering problem with Angular HTTP services: the requested URL is not

Attempting to send data to API servers is resulting in a 404 error. Testing it on Postman shows that everything works fine. JSONP is being used for posting data due to cross-domain issues. The console displays the following: GET http://myapi.com/registrat ...

What is the best way to share image data between pages in Next.js?

I'm currently developing a project that mimics Instagram (simply because I want to explore Next.js further) and I'm looking for a way to handle image uploads. My goal is to allow users to upload their images and then redirect them to the "create ...

How can I incorporate leap years and months with 30 days into a custom date picker dropdown menu?

Looking to create a custom date picker using drop downs. The goal is to only show the correct number of days for each month - 30 days for April, June, September, and November; 29 days for February during a leap year; and 31 days for all other months. Afte ...

Bidirectional updates in AngularJS with CSS styling

On the backend, certain HTML elements store their position and size persistently and retrieve them when the page loads. These elements can be dragged and resized by users, with any updates needing to be saved on the backend for consistency across sessions. ...

Guidelines for capturing a div screenshot with javascript

Let's say I have a div containing an image source. <div> <p class="row">With custom CSS</p> <img src="/images/midhun.jpg"> </div> When a button is clicked, I want to display a screenshot of this image in another div. C ...

Angular is reporting that the check-in component is nonexistent

I encountered an error in my Angular 8 application while working on a component. The error seems to be related to nested components within the main component. It appears that if the component is empty, the error will be shown, but if it's not null, th ...

When using the HTML5 input type time in Chrome and the value is set to 00:00:00, it may not be fully completed

After inputting the html code below <input id="time_in" type="time" step="1" name="duration"> and setting the value in the browser to "00:00:00", everything appears fine. However, upon inspecting the console or submitting the form, the value gets ...