Changing the value of a variable after iterating through an array in JavaScript

I'm just getting started with programming and teaching myself. I'm struggling to grasp how to update a variable by iterating through an array.

Here's an array containing the best pies, each with its own price:

[blueberry, strawberry, pumpkin, apple]

I want the total to increment based on the price using conditional statements, like this:

    var total = 0
    arr.map(pie => {
    if (pie==="blueberry") {
    total = total + 2.5;}
    else if (pie === "apple") {
    total = total + 2}}

However, the total only reaches 2.5 before resetting to 0. So instead of 4.5, I end up with a total of 2 because "apple" was the last pie. :(

What causes this issue, and how can I ensure the total is preserved and continues to accumulate the prices of the other pies?

Answer №1

let items = ['blueberry', 'strawberry', 'pumpkin', 'apple']
var total = 0

items.forEach(item => {
    if (item==="blueberry") {
    total += 2.5;
    }
    else if (item === "apple") {
    total += 2
    }
});

console.log(total)

Instead of utilizing map function, consider using forEach instead.

A brief explanation is as follows:

forEach() — executes a provided function once for each array element.

map() — creates a new array with the results of calling a provided function on every element in the calling array.

Answer №2

It seems like your example is still giving an output of 4.5. However, it might be beneficial for you to check out the API documentation for javascript to gain a better understanding of it.

Here, the map function allows you to create another array from the current one. If you want to keep your existing code, you can simply switch from using .map() to .forEach().

var arr = ['blueberry', 'strawberry', 'pumpkin', 'apple']
var totalMap = 0;
var totalForeach = 0;
arr.map(pie=>{
    if (pie === "blueberry") {
        totalMap = totalMap + 2.5;
    } else if (pie === "apple") {
        totalMap = totalMap + 2;
    }
});
arr.forEach(pie=>{
    if (pie === "blueberry") {
        totalForeach = totalForeach + 2.5;
    } else if (pie === "apple") {
        totalForeach = totalForeach + 2;
    }
});
console.log('map total:',totalMap);
console.log('forEach total:', totalForeach);

Answer №3

As previously stated by Issac, it is generally frowned upon to use the map function for side effects such as updating an accumulator. However, the example you provided should function correctly as shown below:

let arr = ['blueberry', 'strawberry', 'pumpkin', 'apple']
var total = 0

arr.map(pie => {
  if (pie==="blueberry") {
    total = total + 2.5;}
  else if (pie === "apple") {
    total = total + 2}
})

console.log(total)

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

Comparison between a Typescript optional field and a field that has the potential to be undefined

Can you clarify the contrast between an optional field and a T | undefined field? export interface Example { property1: string | undefined property2?: string } ...

Reveal the MongoDB database connection to different sections within a Next.js 6 application

Currently developing an application using Next.js v6, and aiming to populate pages with information from a local mongodb database. My goal is to achieve something similar to the example provided in the tutorial, but with a twist - instead of utilizing an ...

A guide on setting up dual observables in Angular 2

Currently, I am implementing Observable in angular 2 with rxjs. As part of my demonstration, I have utilized fromEvent in a Plunker. Here is the link to my demo: https://plnkr.co/edit/zkgEcdn21CvIKoOycUOy?p=preview In this demo, I have included two input ...

Is there a way to continuously click on a button 99 times or until the code finishes running?

Need Assistance, Please Assist. I am encountering an issue where I have the same type of skip button with identical name and id properties for all products, but only the xpath changes. Can you provide guidance on how to efficiently click on 99 similar ski ...

Issue with Checkbox Functionality Between Parent and Child Components in React.js

In the main component, I have four checkboxes. My goal is to display a value from a function in the child component based on whether each checkbox is checked or not. export default class App extends Component { constructor(props) { super(props); ...

js.executeScript produces a Unexpected identifier error

Visit this link for proofs Running a script in the browser console on the specified page: let img = document.querySelector('.subscribe'), style = img.currentStyle || window.getComputedStyle(img, false), bi = style.backgroundImage.slice(4, -1).re ...

Tips for presenting random images from an assortment of pictures on a webpage

I'm looking to enhance my website by adding a unique feature - a dynamic banner that showcases various images from a specific picture pool. However, I'm unsure of how to find the right resources or documentation for this. Can you provide any guid ...

Display the printed outcome in a fresh window

HTML: <form id="dbview" method="post" action="core/process.php"> .... <p style='text-align:center;'> <input id='delete' type='submit' name='process' value='Delete selected'/> < ...

Is there a way to trim JSONP data to only obtain the year value

My current setup involves using an API to fetch data, which includes the release date of a game. '<h4 style="display:inline-block; padding-left:5px;" class="post-title">' + game.name + ' <span class="small">' + game.origin ...

Having trouble getting the JQuery Tipsy tooltip to display correctly with D3.js circles?

Below is the d3.js code that I have used: var circles = vis.selectAll("circle").data(data) circles .enter() .append("svg:circle") .attr("stroke", "black") .attr("cx", function (d) { return xRange(d.year); }) ...

Tips on converting mysql results to JSON using PHP

mysql database table structure: ID >> Name >> Salary The variable $row_set holds information from the database table. However, when using: json_encode($row_set); The output is in this format: [{"0":"1","ID":"1","1":"x","Name":"x","2":"123 ...

Compute the total value stored in a sqlite database and display the result

I have developed a straightforward API using Express along with SQLite. The database is ready, and I successfully imported data from a CSV file containing information like this: |Timestamp |Email |Name |Year|Make |Model |C ...

Mastering the art of counting down using a forEach loop in JavaScript

Trying to iterate through a list of objects, I can't index it, but can use forEach. My issue is I need to start from the last object and go to the first, but unsure how to achieve that with the forEach function. If I used a for loop, it would be like ...

Using jQuery, we can replace all `<span>` elements with `<img>` elements and then verify if the images have been successfully loaded

Similar Inquiry: jQuery check if image is loaded I find myself in a scenario where the following HTML structure is utilized: <div class="image"> <img class="" src="content-images/1.jpg"> <span class="slide" rel="content-images/ ...

Encountered a TypeError in React 16.7: The function (0, _react.useState) is not recognized

Error: TypeError: (0 , _react.useState) is not a function React versions currently being used: "react": "^16.7", "react-dom": "^16.7", File src/App.js: import {memo, useState} from 'react' export default memo(() => { useS ...

Tips on implementing v-show within a loop

Hey @zero298, there are some key differences in the scenario I'm dealing with. My goal is to display all the items in the object array and dynamically add UI elements based on user input. Additionally, v-if and v-show function differently (as mentione ...

Generate unique div elements randomly using jQuery and Javascript to populate a container

My website has a section that spans 100% width and is 450 pixels tall. This is the HTML structure... <section class="interactive-banner"> <figure></figure> </section> I am aiming for each 'figure' element to be 150 ...

Bringing joy to a JS library: Embracing both Node and the Window

I have developed a JS library that I want to convert into a Node module for use with Node.js. This library extends the Canvas context API and relies on the use of getImageData(). Therefore, it begins with a defensive check to ensure compatibility: if (wi ...

Is there a delay in using ngShow and ngClick for authentication in AngularJS and Firebase?

Just getting started with AngularJS and encountering an unusual issue with Firebase authentication. The basic setup displays the current user status (logged in or not) along with options to sign in and out. Oddly, when I click the Log-in button for the fi ...

Transforming the text to a new line

I have been attempting to format lengthy texts from a JSON file, but I haven't been successful. The text keeps displaying as multiple sections within a single response, which can be seen in the image below. I've tested solutions like word-break a ...