Guide to utilizing Reduce for obtaining a fresh Array of Objects in Javascript

I am a beginner in coding, so I apologize if this question seems basic. I am working with an array that contains different types of pies along with their prices:

pieArr = [blueberry, strawberry, pumpkin, apple]

My goal is to create an array of objects representing the total cost of the shopping cart based on the pie prices. A helpful user on stack overflow suggested using the reduce method for this task.

Here is my current code snippet:

var total = 0;

const totalArr = pieArr.reduce((totalPrice, pie) => {
  if ( pie === "blueberry") {
    total += 2.5;
    totalPrice.push({["cartTotal"]:total});
    return totalPrice;
  }
 else if (pie === "apple") {
   total += 2;
   totalPrice.push({["cartTotal"]:total});
   return totalPrice;
 }, 
 [])};

My desired outcome is a new array of objects that continuously accumulates the total cost:

[{cartTotal:2.5},{cartTotal:4.5}]

Although the new array of objects is created, the total amount is not being properly calculated, resulting in both totals being 0:

[{cartTotal: 0},{cartTotal: 0}]

I am struggling to figure out what I am doing wrong. Any guidance would be appreciated.

Answer №1

An effective method to achieve this is by implementing a price lookup system, such as the following:

let piePrices = {
    blueberry: 2.25,
    strawberry: 1.5, 
    pumpkin: 3,
    apple: 2
}

With this in place, you can utilize the map() method (which is more efficient than using reduce() when creating an array from an existing array), eliminating the need for extensive if/else statements:

let piePrices = {
    blueberry: 2.25,
    strawberry: 1.5, 
    pumpkin: 3,
    apple: 2
}

let pieArr = ['blueberry', 'strawberry', 'pumpkin', 'apple']

let total = 0
let totalPrice = pieArr.map(pie =>  ({cartTotal: total += piePrices[pie]}))

console.log(totalPrice)

Answer №2

const total = 0;
let pieArr = ['blueberry', 'strawberry', 'pumpkin', 'apple']
const totalArr = pieArr.reduce((totalPrice, pie) => {
  let foundPie = totalPrice.find(x => x.name === pie) || {name: pie, total: 0};
  
 if ( pie === "blueberry") {
    foundPie.total += 2.5;
 }
 else if (pie === "apple") {
   foundPie.total += 2;
 }
 
 if(!totalPrice.some(x=>x.name === pie)){
   totalPrice.push(foundPie)
 }
  return totalPrice;
}, []);

console.log(totalArr)

Consider adding a name attribute for better clarity. Within the reduce function, search for the pie in the accumulated totalPrice array, then calculate the sum and check whether to add the element to the accumulated array.

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 initial attempt at using Ajax inside onbeforeunload is unsuccessful

I have attempted to attach the beforeunload event by executing the subsequent script in order to use AJAX to navigate to a specific URL. However, I am encountering an issue where AJAX does not work the first time when I refresh the page, as the URL is no ...

Mastering Vue 3: Simplifying a reactive array of objects while maintaining reactivity

Struggling with maintaining reactivity in Vue 3 when flattening a nested array of objects. Unfortunately, my attempts result in crashing and browser hang-ups. In my Vue 3 component, I have an array structured as a list of objects: this.grouped = [ ...

Purge precise LocalStorage data in HTML/JavaScript

How can a specific item in the localStorage be cleared using javascript within an html file? localStorage.setItem("one"); localStorage.setItem("two"); //What is the method to clear only "one" ...

Utilizing JavaScript to handle the value from a selected form

My form is quite simple: <form id="signup"> <div class="form-group"> <input type="text" name="email" placeholder="Email" id="email" required> </div> <div class="form-group"> <input type= ...

"Learn how to create a scrolling div using a combination of CSS and JavaScript with absolute and relative

After relying solely on "pre-made" components like Mui or TailWind, I decided to create a component using only CSS and maybe JavaScript. However, I encountered some difficulties when attempting to position a div inside an image using relative and absolute ...

Using a JavaScript variable to be displayed in a PHP code

Can someone please help me troubleshoot this code? I am attempting to display a JavaScript variable in PHP after applying a regex, but I keep getting the error Uncaught TypeError: document.getElementById(...).html is not a function $.post('display.ph ...

Discover content within nested arrays - angularJS

I have a function written in angularJS that utilizes find to verify the presence of an item in an array; function checkCartItem(item) { return $scope.cart[0].cart_items.find(function(itm) { return itm.item_id === item.item_id }); } The fu ...

Leveraging the power of AJAX with either jquery or plain javascript to parse nested JSON data and display the

Similar Question: jquery reading nested json I am seeking a reliable method to iterate through multiple sets of data stored in JSON, some of which may have deep levels of nesting. My goal is to display this data in a table format. I am uncertain abou ...

Attach the element to the bottom of the viewport without obstructing the rest of the page

My challenge is to create a button that sticks to the bottom of the viewport and is wider than its parent element. This image illustrates what I am trying to achieve: https://i.stack.imgur.com/rJVvJ.png The issue arises when the viewport height is shorte ...

Transferring documents using JavaScript

I have been using the following method to upload files to my Laravel backend: setFile(id, e) { let self = this; let reader = new FileReader(); reader.readAsDataURL(e.target.files[0]); reader. ...

Embed a static label inside an input field that remains constant even while text is inputted, without using a placeholder. Crafted using HTML,

Take a look at the screenshot below - what you see on the left side is my current setup, while on the right side is the desired outcome achieved without any plugins or HTML5 attributes The left side scenario occurs when I have 2 input fields - one with th ...

Enhancing Vuejs Security: Best Practices and Tips for Secure Development

Recently, I developed a Web Application utilizing Vue.js and fetching data from the backend using 'vue-resource' in combination with Express and Postgres. Now, my main objective is to enhance its security by integrating an API Key. I am somewha ...

Clickable Angular Material card

I am looking to make a mat-card component clickable by adding a routerlink. Here is my current component structure: <mat-card class="card" > <mat-card-content> <mat-card-title> {{title}}</mat-card-title> &l ...

Understanding the concept of "this" within a callback situation

Given class functions game.PlayScreen = me.ScreenObject.extend({ onResetEvent: function() { this.setAll(); //calls setAll(), which calls setGlobals() this.saveNextLevelData(this.setAll); }, saveNextLevelData : function (cal ...

Differentiating the texture of a pointCloud in three.js shaderMaterial: A step-by-step guide

Utilizing THREE.PointCloud for optimum performance, I aim to animate 100,000 objects. However, I am facing an issue with setting different textures for particles. How can I incorporate uniforms with various textures in this code? Is it possible to pass s ...

Is it possible to encounter the issue of "Context Lost" and "Importing multiple instances" in Three.js?

I am in the process of developing a 3D editor that allows users to manipulate a 3D scene and then view the result by pressing a "play" button. In order to display the output, I am utilizing an iframe. Below is the snippet of my HTML code: <iframe id=&qu ...

HTML link with "mailto:" not opening in a new tab

Just posted for the first time! I'm attempting to create a mailto link using 'templated' JavaScript that pulls specific data from a JSON object: var menu = { "menu": [ { "title": "let's talk", "link": "mailto:<a href ...

The process of uploading a file is interrupted by an AJAX Timeout

My HTML form includes a file input field that utilizes AJAX to upload the selected file, complete with a progress bar. However, I encountered an issue where the request would hang without any response. To prevent this from happening in the future, I aim t ...

Validating the length of form inputs and selected items from a dropdown menu

I have the following form and I am attempting to validate its states as follows: themeName is required and should have a minimum of 4 characters. themeLangFrom selected value cannot be the same as themeLangTo (and vice versa). I want to display a span er ...

retrieve data from an asynchronous request

Utilizing the AWS Service IotData within an AWS Lambda function requires the use of the AWS SDK. When constructing the IotData service, it is necessary to provide an IoT endpoint configuration parameter. To achieve this, another service is utilized to obta ...