Filter an array containing objects within objects and use the reduce method to calculate the total value

Here is an array of objects that I'm working with:

     const data = [
     {
        "order_id":38795,
        "order_type":"Music",
        "date":"2021-08-14",
        "name":"Concert",
        "tickets":[
           {
              "id":9,
              "ticket_type":"Priority",
              "quantity":2,
              "price":25,
              "detail":{
                 "Adults":1,
                 "Children":0,
              }
           },
           {
              "id":10,
              "ticket_type":"Priority",
              "quantity":1,
              "price":10,
              "detail":{
                 "Adults":0,
                 "Children":1,
              }
           },
           {
              "id":10,
              "ticket_type":"Standard",
              "quantity":3,
              "price":15,
              "detail":{
                 "Adults":1,
                 "Children":0,
              }
           }
        ]
     },
     {
        "order_id":84874,
        "order_type":"Film",
        "date":"2021-08-14",
        "name":"Adventure",
        "tickets":[
           {
              "id":7,
              "ticket_type":"Standard",
              "quantity":1,
              "price":20,
              "detail":{
                 "Adults":1,
                 "Children":0,
              }
           }
        ]
     }
  ];

I am looking to calculate the total quantity of Adult tickets for orders with the 'Music' order type.

In this scenario, the answer would be 5 (2 * Adult Priority and 3 * Adult Standard)

To begin, I have used the filter method on the array to extract only the 'Music' order_type

const musicOrders = data.filter((order) => {
    return order.order_type == 'Music'
});

When it comes to summing up the quantities, I believe using the reduce method will iterate through the quantity values.

.reduce((total, ticket) => {
    return total + ticket.quantity;
}, 0)

However, I am unsure how to combine filtering by both

order_type = "Music"
ticket.detail.Adults = 1 / true

And retrieving the quantities in a single function. Any suggestions?

Answer №1

If you're looking to find information related to "Music" in an array, you can utilize Array.prototype.find(). Following that, employ Array.prototype.reduce() in the following manner:

const data = [
     {
        "order_id":38795,
        "order_type":"Music",
        "date":"2021-08-14",
        "name":"Concert",
        "tickets":[
           {
              "id":9,
              "ticket_type":"Priority",
              "quantity":2,
              "price":25,
              "detail":{
                 "Adults":1,
                 "Children":0,
              }
           },
           {
              "id":10,
              "ticket_type":"Priority",
              "quantity":1,
              "price":10,
              "detail":{
                 "Adults":0,
                 "Children":1,
              }
           },
           {
              "id":10,
              "ticket_type":"Standard",
              "quantity":3,
              "price":15,
              "detail":{
                 "Adults":1,
                 "Children":0,
              }
           }
        ]
     },
     {
        "order_id":84874,
        "order_type":"Film",
        "date":"2021-08-14",
        "name":"Adventure",
        "tickets":[
           {
              "id":7,
              "ticket_type":"Standard",
              "quantity":1,
              "price":20,
              "detail":{
                 "Adults":1,
                 "Children":0,
              }
           }
        ]
     }
  ];

  
  const res = data.find(item => item.order_type === 'Music').tickets.reduce((acc, curr) => {
    acc += curr.quantity * curr.detail.Adults;
    return acc;
  }, 0);

  console.log(res);

Answer №2

My approach involves utilizing the double Array.prototype.reduce() method to meet the requirement of only calling one parent function.

It seems challenging to achieve this using just a single function due to the presence of nested (multiple) arrays that require iteration.

const data= [{order_id:38795,order_type:"Music",date:"2021-08-14",name:"Concert",tickets:[{id:9,ticket_type:"Priority",quantity:2,price:25,detail:{Adults:1,Children:0,},},{id:10,ticket_type:"Priority",quantity:1,price:10,detail:{Adults:0,Children:1,},},{id:10,ticket_type:"Standard",quantity:3,price:15,detail:{Adults:1,Children:0,},},],},{order_id:84874,order_type:"Film",date:"2021-08-14",name:"Adventure",tickets:[{id:7,ticket_type:"Standard",quantity:1,price:20,detail:{Adults:1,Children:0,}}]}];

const result = data.reduce(
  (acc, curr) =>
  (acc +=
    curr.order_type === "Music" &&
    curr.tickets.reduce(
      (acc, curr) => acc + curr.detail.Adults * curr.quantity,
      0
    )),
  0
);

console.log(result);

Answer №3

To implement the Array.prototype.reduce function, you can use the following approach:

The main reduce function first looks for items with order_type == 'Music', while the nested reduce function calculates the total quantity where the attribute Adults > 0.

const data = [     {        "order_id":38795,        "order_type":"Music",        "date":"2021-08-14",        "name":"Concert",        "tickets":[           {              "id":9,              "ticket_type":"Priority",              "quantity":2,              "price":25,              "detail":{                 "Adults":1,                 "Children":0,              }           },           {              "id":10,              "ticket_type":"Priority",              "quantity":1,              "price":10,              "detail":{                 "Adults":0,                 "Children":1,              }           },           {              "id":10,              "ticket_type":"Standard",              "quantity":3,              "price":15,              "detail":{                 "Adults":1,                 "Children":0,              }           }        ]     },     {        "order_id":84874,        "order_type":"Film",        "date":"2021-08-14",        "name":"Adventure",        "tickets":[           {              "id":7,              "ticket_type":"Standard",              "quantity":1,              "price":20,              "detail":{                 "Adults":1,                 "Children":0,              }           }        ]     }  ],
      countQty = (at, {quantity, detail: {Adults}}) => at + (Adults > 0 ? quantity : 0),
      result = data.reduce((a, {tickets, order_type}) => {
         return a + (order_type == "Music" ? tickets.reduce(countQty, 0) : 0);
      }, 0);
  
console.log(result);

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

Sending data from PHP to JavaScript using JSON encoding through POST requests

I am dealing with a multi-dimensional array that needs to be passed to a PHP script using JavaScript to parse JSON data and display it on Google Maps. I am experimenting with using forms to achieve this: <?php $jsontest = array( 0 => array( ...

What could be the reason my ImageMapster jquery plugin is not functioning in the Power Apps portal's code editor?

I'm attempting to add hover effects to an image map within my Power Apps portal site using the code editor. However, when I include the script: <script type="text/javascript">$('img').mapster();</script> for the desire ...

Unable to locate a type definition file for module 'vue-xxx'

I keep encountering an error whenever I attempt to add a 3rd party Vue.js library to my project: Could not find a declaration file for module 'vue-xxx' Libraries like 'vue-treeselect', 'vue-select', and 'vue-multiselect ...

The function was not invoked as expected and instead returned an error stating "this.method is not

I need help with an issue in my index.vue file. The problem lies in the fancy box under the after close where I am trying to call the messageAlert method, but it keeps returning this.messageAlert is not a function Can someone please assist me in resolving ...

The functionality to scroll to the top of the page is not functioning properly in Next.js when navigating to a new page using the Link

While using Next.js, I encountered an issue where opening a new page would maintain the scroll position from the previous page. For instance, if I had scrolled to the bottom of a product listing page and clicked on a specific product, the product details p ...

What is the solution for correcting the fixed footer in jQuery Mobile?

My experience with jQueryMobile has led me to encounter a couple of persistent bugs even after including data-role="footer" data-position="fixed" in the markup: The footer toggles on a null click event. The footer remains unfixed and ends up hiding some ...

AngularJS nested menu functionality not functioning properly

I am currently working on a nested menu item feature in AngularJS. I have a specific menu structure that I want to achieve: menu 1 -submenu1 -submenu2 menu 2 -submenu1 -submenu2 angular.module('myapp', ['ui.bootstrap']) .cont ...

Why does one image render while the other with the same src does not?

Has anyone encountered a situation where there are 2 img tags with the same src, "images/export.png", but one displays correctly while the other doesn't? Any insights on how this discrepancy can occur? https://i.sstatic.net/z6rnW.png Here's som ...

Angular fails to function properly post rendering the body using ajax

I recently created a HTML page using AJAX, and here is the code snippet: <div class="contents" id="subContents" ng-app=""> @RenderBody() @RenderSection("scripts", required: false) </div> <script src="http://ajax.googleapis.com/ajax/ ...

I am having issues with Hot Reload in my React application

My app was initially created using npx create-react-app. I then decided to clean up the project by deleting all files except for index.js in the src folder. However, after doing this, the hot reload feature stopped working and I had to manually refresh the ...

The particular division is failing to display in its designated location

This is quite an interesting predicament I am facing! Currently, I am in the process of coding a website and incorporating the three.js flocking birds animation on a specific div labeled 'canvas-div'. My intention is to have this animation displa ...

Tips on dividing the information in AngularJS

Sample JS code: $scope.data={"0.19", "C:0.13", "C:0.196|D:0.23"} .filter('formatData', function () { return function (input) { if (input.indexOf(":") != -1) { var output = input .split ...

Learn the best way to handle special characters like <, >, ", ', and & in Javascript, and successfully transfer escaped data from one text box to another

I am seeking a way to use JavaScript to escape special characters. I came across a code snippet on this URL: http://jsperf.com/encode-html-entities. It successfully handles <>&, but I have encountered an issue with double quotes ("). The JavaScri ...

What is the process for removing globally declared types in TypeScript definitions?

There are numerous libraries that cater to various platforms such as the web, Node servers, and mobile apps like React Native. This means they can be integrated using <script /> tags, require() calls, or the modern import keyword, particularly with t ...

The show/hide jquery function is functioning perfectly on desktop devices, but issues arise on mobile devices where the divs overlap each other when using the show() method

I need a way to toggle input text boxes based on selection using a select box This is the HTML code snippet: <div class="row"> <div class="form-group"> <div class="col-sm-1 label2"> <label class="control-label ...

Adjusting hyperlinks placement based on window size changes using jQuery

On resizing the screen, I am moving the sub-nav links to the '#MoreList' It works well initially, but when the window is expanded again, the links remain in the #MoreList instead of going back to their original positions if there is enough space ...

Do Material-UI pickers only validate on blur, not on change events?

When you type inside the DatePicker component, validation is triggered immediately. Is there a way to trigger validation on blur instead of onChange when using @material-ui/pickers with material-ui v4 Passing the value to the blur function should work a ...

Activate JavaScript validation

Within each section (displayed as tabs), I have a custom validator. When one tab is active, the other is hidden. To proceed to submission, I need to disable client validation for the inactive tab. I attempt to do this by calling ValidatorEnable(, false); ...

Having trouble with ng-click not correctly updating values within ng-repeat

Here is the code snippet: <div ng-repeat="data in products"> <div class=edit ng-click="dataUI.showEdit = true; content = data;"> </div> <div ng-repeat="renew in data.renewed"> <div class=edit ng-click="dataUI ...

Issue communicating with connect-flash: flash variable is not recognized

I've been diving into books on node.js, express, and mongodb lately. In one of the examples, the author showcases the usage of connect-flash. However, I'm encountering some difficulties getting it to function as expected. Below are snippets from ...