Choosing based on conditions within a function

I am currently working with an object that contains orders from a restaurant.

   var obj = {
      orders: [
        null,
        {
          date: "2018-07-09 10:07:18",
          orderVerified : true,
          item: [
            {
              name: "apple juice",
              price: 3.9,
              quantity: 1,
              isDrink: true 
            },
            {
              name: "Hawaii pizza",
              price: 7,
              quantity: 2,
              isDrink: false
            }
          ]
        },
        {
          date: "2018-07-09 10:07:30",
          orderVerified : false,
          item: [
            {
              name: "Warmer Topfenstrudel",
              price: 3.9,
              quantity: 1,
              isDrink: false
            }
          ]
        },
        {
          date: "2018-07-09 15:07:18",
          orderVerified : true,
          item: [
            {
              name: "Coca Cola 2 l",
              price: 12.9,
              quantity: 3,
              isDrink:true
            }
          ]
        },
        {
          date: "2018-06-13 10:07:18",
          orderVerified : true,
          item: [
            {
              name: "Wiener Schnitzel vom Schwein",
              price: 9.9,
              quantity: 2,
              isDrink: false
            }
          ]
        }
      ]
    };

I need to calculate the total price of all drinks in the orders by multiplying their individual prices and quantities when isDrink is true. Although I have tried using the function provided below to sum up the total items cost, I faced difficulties distinguishing between drinks and non-drinks in order to compute the final amount.

 fullTotal: function(arr) {
    if (arr!=''){
    return arr.reduce((sum, order) => {
      return sum + order.item.reduce((itemSum, item) => (
        itemSum + (item.price * item.quantity)
      ), 0)
    },0)}
    else {return 0}
  },

I would appreciate any suggestions or guidance on how to approach this issue. Thank you!

Answer №1

To successfully achieve your goal:

  • Remove any null values from the array
  • Exclude items that are not drinks based on the isDrink property

var obj = {
  orders: [
    null,
    {
      date: "2018-07-09 10:07:18",
      orderVerified: true,
      item: [{
          name: "apple juice",
          price: 3.9,
          quantity: 1,
          isDrink: true
        },
        {
          name: "Hawaii pizza",
          price: 7,
          quantity: 2,
          isDrink: false
        }
      ]
    },
    {
      date: "2018-07-09 10:07:30",
      orderVerified: false,
      item: [{
        name: "Warmer Topfenstrudel",
        price: 3.9,
        quantity: 1,
        isDrink: false
      }]
    },
    {
      date: "2018-07-09 15:07:18",
      orderVerified: true,
      item: [{
        name: "Coca Cola 2 l",
        price: 12.9,
        quantity: 3,
        isDrink: true
      }]
    },
    {
      date: "2018-06-13 10:07:18",
      orderVerified: true,
      item: [{
        name: "Wiener Schnitzel vom Schwein",
        price: 9.9,
        quantity: 2,
        isDrink: false
      }]
    }
  ]
};

function calculateTotal(arr) {
  if (arr != '') {
    return arr.filter(order => order != null).reduce((sum, order) => {
      return sum + order.item.filter(item => item.isDrink).reduce((itemSum, item) => (
        itemSum + (item.price * item.quantity)
      ), 0)
    }, 0)
  } else {
    return 0
  }
}

console.log(calculateTotal(obj.orders));

Answer №2

Give this a shot

calculateTotalValue: function(itemsArray) {
    if (itemsArray!=''){
    return itemsArray.reduce((total, order) => {
      return total + order.items.reduce((itemTotal, item) => (
        itemTotal + item.isDrink ? (item.cost * item.quantity) : 0
      ), 0)
    },0)}
    else {return 0}
  },

Answer №3

To ensure accuracy in the calculation, a check for an array is recommended along with verifying the necessary object and isDrink property before summing up the values.

var obj = { orders: [null, { date: "2018-07-09 10:07:18", orderVerified: true, item: [{ name: "apple juice", price: 3.9, quantity: 1, isDrink: true }, { name: "Hawaii pizza", price: 7, quantity: 2, isDrink: false }] }, { date: "2018-07-09 10:07:30", orderVerified: false, item: [{ name: "Warmer Topfenstrudel", price: 3.9, quantity: 1, isDrink: false }] }, { date: "2018-07-09 15:07:18", orderVerified: true, item: [{ name: "Coca Cola 2 l", price: 12.9, quantity: 3, isDrink: true }] }, { date: "2018-06-13 10:07:18", orderVerified: true, item: [{ name: "Wiener Schnitzel vom Schwein", price: 9.9, quantity: 2, isDrink: false }] }] },
    fullTotal = function (array) {
        return Array.isArray(array)
            ? array.reduce((sum, o) => o && Array.isArray(o.item)
                ? o.item.reduce((s, { price, quantity, isDrink }) => s + (isDrink && price * quantity), sum)
                : sum, 0)
            : 0;
    };

console.log(fullTotal(obj.orders));

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

I am having trouble getting my console.log function to work properly on my HTML page

As a beginner in JavaScript, I am facing an issue with my console.log not working at all. When I type a console.log message, nothing shows up on my HTML page. I have tried to debug it, but being a newbie, I lack the necessary knowledge. All I can do is see ...

What is the best way to ensure that a link fragment scrolls to the top of the page in Angular?

Having trouble with link fragments in my Angular single-page-app: <a href="/#/search">Search</a> When clicking this link, it takes me to the right page but keeps my scroll position. I want it to scroll to the top of the page so I'm curre ...

Discover a foolproof method for effortlessly examining an flv or mp4 file embedded within a webpage simply by

I've encountered a challenge with JavaScript. I can successfully check a flash object in a webpage when hovering over it, but I'm unsure how to achieve the same for flv or mp4 objects when either hovering over or moving away from them. Currently ...

Struggling with converting JSON to JAXB with Jackson's ObjectMapper

I've encountered a challenge in my JAX-RS project related to JSON to JAXB deserialization using Jackson's ObjectMapper. The technologies/frameworks being used include: Jackson (FasterXML) 2.8.5 JAXB 2.2 The issue arises specifically with all I ...

The modal remains closed: Error - Attempting to access property 'open' of undefined

I've been attempting to showcase a pop-up that I implemented as a modal, but I keep getting this error: TypeError: Cannot read property 'open' of undefined The pop-up was created as a component: import { Component, OnInit, ViewChild, Ele ...

Adjusting the Depiction Camera Distortion in Three.js

In my top-down Three.js game, I'm currently using a Perspective Camera. However, I've noticed that it curves a bit too much because it's mainly for "first-person view". Is there a way to customize how objects bend or curve within the frustum ...

Best Practices for Safely Storing the JWT Client Credentials Grant

Currently, I am working on a NodeJS Express Application that connects to an Auth Server using client credentials grant. After receiving the token from the Auth Server, I use it to access data from an API. I am seeking advice on the most effective way to s ...

Button in HTML not functioning as expected

I have 3 different files that are crucial for my webpage to function properly: index.html: <html> <head> </head> <body> <h1>Webpage</h1> <p id = "text">Hello world!</p> <button oncl ...

Tips for styling an array of objects using mapping techniques

I have an array of messages and I am currently using the map() function. Each message in the array has two keys - one for the author and another for the message content. What I want to achieve is to change the styles of the div tag when displaying the last ...

Nest a dictionary within a column of a DataFrame

https://i.sstatic.net/946vP.png Struggling to extract the username from the author column of the dataframe for each row, where the author column consists of dictionaries. Converting the author column directly to a DataFrame and changing its type does not ...

When deserializing JSON into a Dictionary in a Web Api, the result is consistently an

I am working with a JSON string that looks like this: {"1":[1,3,5],"2":[2,5,6],"3":[5,6,8]} My goal is to send this JSON string to the Web Api Controller using an ajax request without any changes: $.ajax({ type: "POST", url: "Api/Seriali ...

Oops! There seems to be an issue with trying to access the 'map' property of undefined within the render method

While working on my project, I encountered an issue with a table from react material ui. The problem arises when attempting to populate the table with data from the state, resulting in an error message stating "cannot read property 'map' of undef ...

Steps to temporarily turn off Backbone.sync for a fresh model and then reactivate it once the user clicks the save button

I am currently working with a Backbone collection model that consists of sub-models as elements, along with views to edit it. My objective is to have the syncing functionality "turned off" initially when the model is created, so that the back end is not c ...

I am having difficulty toggling text within a for loop in JavaScript

When I display a list of cards using a for loop and click on them, I want to toggle some text. The issue I'm facing is that it works fine for the top card, but when I click on the card below, it toggles the text of the first card instead. This is desp ...

Using JavaScript to control the state of a button: enable or

In the process of creating a basic HTML application to collect customer information and store it in a database, I have encountered a specific user interface challenge. Once the user logs into their profile, they should see three buttons. Button 1 = Print ...

Implementing CSS counter-increment with jQuery

Is there a way to use jQuery to set the CSS counter-increment attribute on ".demo:before" even though jQuery cannot access pseudo elements directly? I recall seeing a suggestion on Stack Overflow about using a data attribute and then referencing that value ...

What is the best way to flip the direction of the text input for a Calculator?

I am currently working on creating a basic calculator from scratch using HTML, CSS, and JavaScript. I have been trying to figure out how to align the numbers to the right side of the input element. Can anyone provide me with guidance on how to achieve thi ...

What is the reason for the inability to access a global variable type variable outside of the $.each function when used within the $

While analyzing a code snippet, I came across an issue with a variable causing an error. function call(data) { $.each(data, function(index, value) { var ddlId = 'ddlCat' + data[index].docId; var html = '<tr id="supp_doc_row_&ap ...

The concept of navigation and passing parameters in Angular.js

Attempting to customize the standard user module of MeanJS, I added a new route: state('users', { url: '/users/:username', templateUrl: 'modules/users/views/view-profile.client.view.html' }); ...

Having trouble displaying the time in the middle square when pressing TouchableOpacity in React Native?

Having trouble pressing the TouchableOpacity button as it's not responding, and even after pressing it, I need to access the time picker to select a specific time to display inside the square view in the center. Any suggestions on how to resolve this ...