Head and tail tally

I've been working on coding a heads or tails system in JavaScript, but I've hit a roadblock. I am struggling to find a solution.

Here is what I have so far:

const userInput = prompt("Heads or Tails?");
const arr = [0, 0, 1, 1, 1, 0, 1, 0, 1];

arr["Result"] = "heads";
let headCount = 0, tailCount = 0;

for (let i = 0; i < arr.length; i++) {
    if (arr["Result"] === "heads")
        headCount += arr[i];
    else
        tailCount += arr[i];
}

alert("Heads: " + headCount + " " + "Tails: " + tailCount);

I'm struggling to figure out where I went wrong. Any insights or advice would be greatly appreciated.

Thank you

Answer №1

It seems like there might be some confusion with the logic here.

var arr = [0, 0, 1, 1, 1, 0, 1, 0, 1];

So, if 0 represents heads and 1 represents tails, is that correct?

arr["Result"] = "heads";

This line sets the property Result on the array arr to be "heads", but it may not be necessary.

let arr = [0, 0, 1, 1, 1, 0, 1, 0, 1];

let headCount = 0,
  tailCount = 0;

for (let i = 0; i < arr.length; i++) {
  if (arr[i] === 0)
    headCount += 1;
  else
    tailCount += 1;
}

console.log("Heads: " + headCount + " " + "Tails: " + tailCount);

This code snippet will loop through the array and update the counting variables based on the values found in the array.

Answer №2

Building on the insights provided by Eric H's response, another approach is to leverage Array.reduce() and utilize array destructuring for achieving the same outcome:

const array = [0, 0, 1, 1, 1, 0, 1, 0, 1];

const [headsCount, tailsCount] = array.reduce((result, number) => {
  result[number] += 1;
  
  return result;
}, [0, 0]);


console.log("Heads: " + headsCount + " " + "Tails: " + tailsCount);

Answer №3

const flips = [0, 0, 1, 1, 1, 0, 1, 0, 1];

let heads = 0;
let tails = 0;

flips.forEach(flip => flip ? heads += 1 : tails += 1)

console.log(
  `Heads: ${heads}  
Tails: ${tails}`)

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 variable in Angular stopped working after the addition of a dependent component

Currently, I am working with Angular and have implemented two components. The first component is a navigation bar that includes a search bar. To enable the search functionality in my second component (home), I have added the following code: HTML for the n ...

React State Property that looks at properties within its own scope

Can a property within the React state object reference its own properties? Consider the example below: this.state = { currentTotal: 30, columnLength: Math.ceil(this.currentTotal / 3), // Resulting in NaN. } ...

Mystifying WebPack sourcemaps lead to duplicated files

Today, I decided to experiment with WebPack on a new project I'm starting and I'm encountering some unusual behavior with the sourcemaps. Despite checking the documentation and scanning through StackOverflow, I can't seem to find any helpful ...

Ways to update a component from another in React

My React code includes an Employees page that renders both a Table component and a Filter component. The Filter component manipulates some data stored in the Employees page, updates the Filter's state through useEffect, and passes the data as a prop t ...

An error occurred while attempting to retrieve data from a JSONArray

I have been working on creating a phonegap plugin for Android where I am returning a JSONArray using callBackContext.sendPluginResult(result);. Below is the code snippet demonstrating how I am constructing the JSONArray: private JSONArray makeJsonObject(S ...

While attempting to populate an array with integers through iteration, I encountered an ArrayIndexOutOfBoundsException

I've been working on a piece of code to populate an array with integers, but I'm running into some issues. Here's the code I'm using: int[] numbers = new int[1000001]; numbers[0] = 0; numbers[1] = 1; numbers[2] = 2; ...

Wait for the definition of a variable before returning in React Native

I am currently receiving data asynchronously and displaying it within the render() function using {data}. My dilemma is how to ensure that the render() function waits until the variable is defined. Currently, the placeholder variable remains the same or d ...

Adhesive Navigation Bar

Check out this link: JSFIDDLE $('.main-menu').addClass('fixed'); Why does the fixed element flicker when the fixed class is applied? ...

How to iterate through a "for" loop in JavaScript using Python-Selenium?

In my current project, I am utilizing Javascript to gather data from an HTML page using Selenium. However, I am facing a challenge where I am unable to execute the multi-line for loop in the Javascript portion on my computer through Selenium with Python (S ...

Guide on transforming Div content to json format with the use of jquery

I am trying to figure out how to call the div id "con" when the export button is clicked in my HTML code. I want it to display JSON data in the console. If anyone has any suggestions or solutions, please help! <html> <div id ="con"> < ...

Converting an array of numbers in a series to a single normal number in Python

https://i.stack.imgur.com/ddh1K.jpg I am trying to extract only the number of days from the recency column by converting it to a string and using the split function to get the first part, which is a["recency"].str[:1]. However, I am facing an is ...

Multiple Class Changing Effects: Hover, Fade, Toggle

I have a simple yet complex problem that I am trying to solve. I want to create links that fade in upon mouseover and fade out when the mouse moves away. Simultaneously, I want an image to slide in from the left while hovering over the links. I have manage ...

Error: The fetch API encountered an unexpected termination before completing the request

A new issue has come up in my project, and although I found a similar problem on this link, it does not address my specific issue. What I have set up is a straightforward API using nodejs, express-framework, and mongoose. The issue lies with the fetch API ...

Run javascript code after the page has transitioned

Struggling to create a dynamic phonegap app with jQuery Mobile, the issue arises when loading JavaScript on transition to a new page. The structure of my index page is as follows: <body> <div data-role="page" id="homePage"> <div data- ...

What is the best way to switch between components in vue.js?

I have created a Dashboard.vue component consisting of two child components: DisplayBooks.vue and sortBooksLowtoHigh.vue. Initially, the sortBooksLowToHigh component is hidden while the displayBooks component is visible by default. The requirement is that ...

Issues with the functionality of socket.io and node.js are causing problems

Currently, I am experimenting with building apps using socket.io and node.js. Specifically, I am working on a basic "log in" application, but it seems to be encountering some issues. Every time I launch the app, a "404 not found" message appears in the Chr ...

"I am interested in using the MongoDB database with Mongoose in a Node.js application to incorporate the

I am facing a situation where I need to validate the name and code of a company, and if either one matches an existing record in the database, it should notify that it already exists. Additionally, when receiving data with isDeleted set to true, I want to ...

Creating a multi-step form in Rails without using the Wizard gem allows for more

My Rails 3.2.14 app gathers call data and the new/edit action form is quite lengthy on a single page. I am interested in implementing a multistep form using JS/client side processing to navigate between steps. While considering the Wicked Gem for multi-ste ...

Ensure that Ajax requests are successfully executed when a user navigates away from the page

I have developed an HTML/JavaScript application that requires an AJAX request to be made when the user refreshes or closes the page in order to close the application gracefully. To achieve this, I am using the pageunload event. I have implemented the func ...

What is the most effective method for achieving a desired outcome?

Is it a valid approach to get an action result, and if so, how can this be achieved? For instance, if there is a page with a form for creating entities, after successfully creating an entity, the user should be redirected to the entity's detail view. ...