Calculating a bowling score by looping through a JavaScript array

Currently, I am working on developing a bowling scoring application and have encountered difficulty in calculating the strike score. In bowling, when a player scores a strike, they earn 10 points for that roll along with the points for the next two rolls. My challenge lies in iterating over the array of scores to correctly compute the total score. For instance, the array of scores I am working with is as follows:

scores = [10, 1, 5, 1, 2, 10, 5, 2, 10, 10, 8, 1, 10, 3, 2] 

My goal is to loop through the array and whenever a score of 10 is encountered, add the values of the next two rolls to the total score. I have attempted to write the following code:

for (i = 0; i < scores.length; i++) {
    if(scores[i] == 10){
    result += scores[i + 2]
    }
  return result
}

Unfortunately, this code does not perform as expected. As I am very new to Javascript, any guidance on improving this code would be greatly appreciated!

P.S. I am aware that a traditional bowling game includes a tenth frame bonus, which I plan to implement in the future.

Thank you in advance for your assistance!

Answer №1

function calculateTotal(arrayOfScores) {
    let total = 0;
    for (i = 0; i < arrayOfScores.length; i++) {
        if (arrayOfScores[i] == 10) {
            total += arrayOfScores[i + 2] + arrayOfScores[i + 1];
        }
        total += arrayOfScores[i];
    }
    return total;
}


calculateTotal([1, 5, 10, 3, 2]);

Make sure to include additional check on your own as well.

Tip: Confirm that the next 2 values exist in the array before adding them to the total. This function will generate an error if the last value is 10.

Answer №2

Make sure to keep the variable result outside of your loop

let result = 0;

for (i = 0; i < scores.length; i++) {
  if (score[i] === 10) {
    result += scores[i + 1];
    result += scores[i + 2];
  }

  result += score[i];
}

You can also take a more functional approach:

function calculateTotal(scores) {
  let result = 0;

  scores.forEach((score, index) => {
    if (score === 10) {
      result += scores[index + 1];
      result += scores[index + 2];
    }

    result += score;
  });

  return result;
}

Or utilize Array.reduce() for a different solution:

function calculateTotal(scores) {
  return scores.reduce((accumulator, currentValue, index) => {
    if (currentValue === 10) {
      return accumulator + currentValue + scores[index + 1] + scores[index + 2];
    }

    return accumulator + currentValue;
  }, 0);
}

Answer №3

let totalScore = 0;

for (let index = 0; index < playerScores.length; index++) {
  if (playerScores[index] === 10) {
    totalScore += (index + 1 < playerScores.length) ? playerScores[index + 1] : 0;
    totalScore += (index + 2 < playerScores.length) ? playerScores[index + 2] : 0;
  }
  totalScore += playerScores[index];
}

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

HTML Date input field not respecting locale settings and defaults to mm/dd/yyyy format

When using an html date input in an ng-repeat scenario, I noticed that it defaults to mm/dd/yyyy even though my computer's regional settings are set to dd/mm/yyyy. <script src="//unpkg.com/angular/angular.js"></script> <body ng-app&g ...

Switching on and off a class in Next.js

I'm a beginner with Next.js and React framework. My question is regarding toggling a class. Here's my attempt in plain JS: function toggleNav() { var element = document.getElementById("nav"); element.classList.toggle("hidde ...

"Is there a way to loop through elements in JavaScript similar to how you

When working in bash, I typically use the following code: for i in {0..2}; do echo x$i; done However, when attempting to replicate this function in JavaScript with the following code: for (var i=0; i<3; i++) { console.log(x$i); }; It is evident t ...

Display issue with ThreeJS cube

Currently, I'm delving into the world of ThreeJS and decided to incorporate the library into my existing NextJS project. My goal was simple - to display a cube on the front page. However, despite my best efforts, nothing seems to be appearing on the s ...

The Ion-icon fails to appear when it is passed as a prop to a different component

On my Dashboard Page, I have a component called <DashHome /> that I'm rendering. I passed in an array of objects containing icons as props, but for some reason, the icons are not getting rendered on the page. However, when I used console.log() t ...

Tips for limiting the size of image uploads to under 2 megabytes

I am trying to implement an html select feature that allows users to upload images. <div class="row smallMargin"> <div class="col-sm-6"> Attach Image </div> <div class="col-sm-6"> <input type="file" ng-model="image" accept=" ...

Is there a way to prevent an iframe from being recorded in Chrome's browsing history?

I'm in the process of developing a Chrome extension that inserts an Angular application into the user's browser window to create an interactive sidebar. I've been successful in most of my goals by inserting an iframe through a content script ...

Exploring the concept of recursion within the PHP language, delving into the intricacies of organizing

Here is a tree structure represented as an array with parent-child relationships: Array ( [0] => Array ( [id] => 12 [address] => root addr [parent_id] => 0 [children] => ...

The background image shifts dynamically with a parallax effect as the page is scrolled

I need help solving a parallax issue that I'm currently facing. On my webpage, I have a background image positioned at the top with a parallax effect achieved through background-position: fixed. However, I now require the image to scroll along with t ...

Sharing data in JavaScript functions

In order to use certain variables in two separate functions, there are some considerations to keep in mind. The first function is responsible for calculating and displaying a conjugated verb using these variables. The second function checks the user's ...

Retrieving the object ID of an Open Graph from a page's URL

Is there a way to obtain the Facebook Object ID associated with a page directly from the page itself? For instance, if I requested the Object ID 325186347604922, this is what I received: <pre> { "url": ".../ricetta-bigne_salati.htm", "type": " ...

Generate Arrays Using the Foreach Method

I'm currently working with a MySQL table that has a column containing JSON data and another column for the amount. My objective is to extract both the JSON data and amount, then create an array within a foreach loop. Take a look at my code snippet bel ...

How can I dynamically display Material-UI's <MenuItem/> within a <DropDownMenu/> using ReactJS?

In my ReactJS + Material-UI project, I am working with an array named colors that contains different color strings such as "white", "blue", and "green. My goal is to render each color string as a <MenuItem/> within a <DropDownMenu/> component ( ...

Execute a Vue.js script once all Axios calls have been resolved

In this scenario, it is necessary to execute the carResult function only after all axios requests have been completed. Placing it inside the success method of method2 won't work because the component ends up executing the code twice. It would be great ...

Tips for maintaining table elements in place using JavaScript

My goal is to keep the tags within the table fixed when printing. The code I've written functions correctly in View mode, however, when printed using JavaScript, if one of the columns is too large, the rest of the columns get displaced. I want all col ...

Tips for fetching form data transmitted via HTTPS in Node.js?

As someone new to back-end security, I'm hoping for some guidance without judgement: When receiving values over HTTP in my node application, the form data is easily accessible in the request object using req.body.{name of input element} However, whe ...

How to Retrieve Checkbox Values from Multiple Rows Using JavaScript

I have a variety of module rows that allow users to manage access rights by selecting specific options. My goal now is to extract the checked boxes from these checkboxes with the name "config{{$field->id}}". Below is the current functioning code. HTM ...

react native is not updating the view even though the state has been changed

Upon opening my component, I am looking to retrieve Assets from a Media Folder (which is currently functional) and then pass them along to another component. However, the issue arises when launching the app for the first time, as the "listOfAssets" state a ...

NodeJS loop issue with variable scoping in the context of express and mongoose

My Tech Stack: NodeJS, express, mongoose var i; for(i = 0; i < results.length; i++){ console.log("out: "+i); RegionData.findOne({'rid': results[i].region_id}, function (err, product) { if (product) { console.log("i ...

monitor the location of a div within a textarea

My question revolves around a textarea that is linked to a draggable div through the following code: $('#content').children().draggable({ drag : function () { $('#textarea').text("left:" +($(this).position( ...