Traversing an object containing an array property using JavaScript loops

I am currently experimenting with a basic BlackJack game using JavaScript. Below are some snippets of my code:

 function card(suit, face) {
    this.suit = suit;
    this.face = face;

    switch (face) {
        case "A":
            this.faceValue = 11;
            break;
        case "J":
        case "Q":
        case "K":
            this.faceValue = 10;
            break;
        default:
            this.faceValue = parseInt(face);
            break;
    }
};

const player = {
    cards: [],
    handValue: 0
}

const dealOneCardToPlayer = () => {     
    tempCard = deck.cards.splice(0, 1);
    player.cards.push(tempCard);
    player.handValue = countHandValue(player.cards);
}

I am facing an issue with the countHandValue method where I'm unable to obtain the faceValue of Cards for the player object. I have attempted various types of for loops but haven't been successful so far. Once I can access the faceValue, I will be able to calculate and assign it to the handValue property.

const countHandValue = (cardsOnHand) => {    
    for (const key of cardsOnHand) {
        console.log(key.faceValue);
    }

    for (const key in cardsOnHand) {
        console.log(key.faceValue);
    }
}

[Code Edited]I came across this sample code that allows me to retrieve the faceValue property, although I believe there is unnecessary complexity in the code:

    const countHandValue = (cardsOnHand) => {
    let sum = 0;
    for (var key in cardsOnHand) {
        var arr = cardsOnHand[key];
        for (var i = 0; i < arr.length; i++) {
            var obj = arr[i];
            for (var prop in obj) {
                if (prop === "faceValue") {
                    console.log(prop + " = " + obj[prop]);
                    sum = sum + obj[prop];                        
                }                    
            }
        }
    }        
    return sum;
}

Answer №1

Keep in mind that A can be valued at either 1 or 11. This code snippet demonstrates how this scenario can be managed -

const add = (x = 0, y = 0) =>
  x + y

const sum = (a = []) =>
  a .reduce (add, 0)

const scoreCard = (face = "") =>
  face === "A"
    ? [ 11, 1 ]
: (face === "K") || (face === "Q") || (face === "J")
    ? [ 10 ]
: [ Number (face) ]

const allScores = ([ face = "", ...more ]) =>
  face === ""
    ? [ scoreCard (face) ]
    : allScores (more)
        .flatMap
          ( hand =>
              scoreCard (face) .map (v => [ v, ...hand ])
          )

const scoreHand = (...hand) =>
{ const [ best = "Bust" ] =
    allScores (hand)
      .map (sum)
      .filter (score => score <= 21)
  
  if (best === 21)
    return "Blackjack!"
  else
    return String (best)
}

console .log
  ( scoreHand ("A", "K")                     // Blackjack!
  , scoreHand ("A", "A", "K")                // 12
  , scoreHand ("A", "A", "K", "7")           // 19
  , scoreHand ("J", "4", "K")                // Bust
  , scoreHand ("A", "A", "A", "A", "K", "7") // Blackjack!
  )

Answer №2

One simple solution is to utilize the reduce method:

const calculateHandValue = cards => cards.reduce((total, { faceValue }) => total + faceValue, 0);

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

Fixing perspective clipping in Three.js

In my Three.js project, I have a plane inside a sphere that I am applying a shader to in order to achieve certain visual effects on the sphere. To ensure that the plane is always facing the camera, I am using the lookAt method. However, I have noticed that ...

Python script for extracting content from web pages that are loaded dynamically

I am facing an issue with extracting content from a webpage on my website. Despite trying to use selenium and clicking buttons, I have not been successful. #!/usr/bin/env python from contextlib import closing from selenium.webdriver import Firefox import ...

AngularJS Date Selection with UI Bootstrap Tool

Just starting out with AngularJS and looking to add a datepicker to my project. I'm using angular.min.js version AngularJS v1.5.0-rc.1 ui-bootstrap-tpls-0.12.0.js version 0.12.0. There are so many examples online that it's confusing. How do I go ...

When iterating through a table, an error occurs stating that the property "rows" is not available on type HTMLElement (

Issue Error TS2339 - Property 'rows' does not exist on type HTMLElement when looping through table in Angular 7 Encountering error when trying to loop through HTML table in Angular 7 Currently working with Angular 7 and facing an error while ...

Is there a way to remove specific mesh elements from a scene in Unity?

When I create multiple mesh objects with the same name, I encounter difficulties in selecting and removing them all from the scene. Despite attempting to traverse the function, I have not been successful in addressing the issue. event.preventDefault(); ...

Dealing with AngularJS ng-model problems when duplicating a form

Currently, I am facing an issue with sending parameters to control and require some guidance. I have multiple types of questions within the ng-repeat loop named 'question' that I am iterating through. The problem arises when there are two questi ...

How to show a placeholder in a select input using ReactJS

I'm currently trying to incorporate placeholder text into a select input field using ReactJS, but it doesn't seem to be working as intended. Here is the code snippet I am working with: <Input type="select" placeholder="placeholder"> ...

Retrieve: Type 'string | undefined' does not match the parameter type 'RequestInfo'

When using the fetch function, I encountered an error with the "fetchUrl" argument: Error: Argument of type 'string | undefined' is not assignable to parameter of type 'RequestInfo'. This is the code snippet where the error occurred: ...

The Tiny Scrollbar jQuery plugin experiences a malfunction when the defer attribute is added to the script tags in the javascript code

After successfully setting up the jQuery plugin, Tiny Scrollbar, I encountered an issue when I attempted to defer the loading of the necessary javascript files. Here is an example of the code snippet: <script type="text/javascript" src="https://ajax.g ...

Encrypting href links in Nodemailer with Handlebars for forwarding purposes

I am working on a project that involves utilizing NodeMailer + Handlebars for sending and tracking emails. I am interested in changing every href link to the project URL before redirecting to the destination link. For example: Original email: <a href ...

What is the best way to implement the node.js function into a typical frontend JavaScript file?

I created a node.js puppeteer script to extract data on covid cases in Canada. Now, I want to integrate this function into a frontend website built with JavaScript to display information on Canada's covid cases. How can I export this function to a Jav ...

Toggle the display of dropdown 2 or dropdown 3 depending on the option chosen in dropdown 1

I am struggling with a form that contains 3 dropdowns: <select id="1" required> <option value="">Choose an option</option> <option value="1">Apple</option> <option value="2">Orange ...

Removing the last two characters from a number with a forward slash in Vue.js

I'm encountering a slight issue with my code: <template slot="popover"> <img :src="'img/articles/' + item.id + '_1.jpg'"> </template> Some of the item.id numbers (Example: 002917/1) contain ...

Converting an INI file into a multidimensional array using PHP

Below is an example of an INI file: x.y.z = 5 x.y.m.n = 10 After parsing the file using the parse_ini_file function, the result is: array( 'x.y.z' => 5, 'x.y.m.n' => 10 ) However, I aim to convert this into a multidime ...

What is the best way to manage DOM modifications in a responsive design layout?

Developing a responsive website with only one breakpoint can be challenging, especially when restructuring the DOM to accommodate different screen sizes. It's important to consider not just CSS and media queries, but also how the elements are arranged ...

Ways to eliminate the dotted line from the image map in Internet Explorer 11

Below you will find the code I am working with: <img alt="Testing 2015" border="0" src="images/Test-2015.jpg" usemap="#Map" /> <p><map name="Map"><area coords="790,100,653,135" href="http://www.google.com/" shape="rect" style="cursor ...

Having issues with clicking on a row in the table while using AJAX functionality

Experiencing a puzzling issue while attempting to add click functionality to table rows with AJAX, here is the JavaScript code used: //for tabs $(document).ready(function () { $("#tabs").tabs(); }); $(window).load(function() { jsf.ajax.addOnEven ...

The MongoDB regex is failing to provide the expected outcome

I'm facing an issue with searching data in MongoDB. I have a table with approximately 5000 entries of data that need to be searched based on multiple columns with specific priority criteria. The first priorities for the search are symbol, name, co_nam ...

Ways to extract Document ID from a Firestore database collection

Currently, I am in the process of developing a mobile app using React Native and Firebase. My main focus right now is on accessing document data without explicitly specifying the ID, unlike the method shown below: const docRef = db.collection('vehicle ...

Problem encountered when closing a lightbox on ASP.net using C# during page load

Can you explain the events that are triggered when the ASP.NET page load event occurs? I am currently using a lightbox for some insertion tasks, and after the insertion is complete, I want the parent page to reload with the new value displayed in the gri ...