combine the values from the card objects

Hello, I am currently new to programming and learning Javascript. I am facing a challenge with a school assignment at the moment. In my code below, I have a function that works when I log one object like this:

score([{ suit: 'HEARTS', value: 1 }])
This returns 11. However, I am unsure how to modify my code to handle multiple objects and add their values together for a combined score. For instance, if I call these objects with values 2, 3, and 4, it should return 9.

score([{ suit: 'HEARTS', value: 2 }, { suit: 'HEARTS', value: 3 }, { suit: 'HEARTS', value: 4 }])

The current implementation of my code is as follows:

let score = function (cardObject) {
  let getScore = 0;

  for (let i = 0; i < cardObject.length; i++) {
   getScore += cardObject[i].value
   
    if (getScore === 1) {
      return 11;
    } else if (getScore === 2) {
      return 2;
    } else if (getScore === 3) {
      return 3;
    } else if (getScore === 4) {
      return 4;
    } else if (getScore === 5) {
      return 5;
    } else if (getScore === 6) {
      return 6;
    } else if (getScore === 7) {
      return 7;
    } else if (getScore === 8) {
      return 8;
    } else if (getScore === 9) {
      return 9;
    } else {
      return 10;
    }
  }
}

Answer №1

Instead of having if statements for each individual number, you can streamline your code by combining them into one statement.

Revised the function based on feedback to account for face cards with an if statement.

The initial if statement covers values ranging from 10 to 13, adding 10 if met. If the card value is 1, add 11. Otherwise, simply add the card's value.

Finally, I return the getScore variable holding the cumulative score.

Your previous code returned the value prematurely, halting the function execution. The correct placement for the return would be at the very end, following completion of all logical operations.

let tally = function(cardDeck) {
  let totalScore = 0;

  for (let i = 0; i < cardDeck.length; i++) {
    let cardVal = cardDeck[i].value;
    if (cardVal >= 10 && cardVal <= 13) {
      totalScore += 10;
    } else if (cardVal === 1) {
      totalScore += 11;
    } else {
      totalScore += cardVal;
    }
  }

  return totalScore;
}

console.log(tally([{
  suit: 'HEARTS',
  value: 10
}, {
  suit: 'HEARTS',
  value: 11
}, {
  suit: 'HEARTS',
  value: 12
}]));

Answer №2

To achieve this, you can utilize the Array#reduce method.

function calculateTotal(arr) {
            return arr.reduce((acc, {value}) => acc + (value === 1 ? 11 : value), 0);
        }
        let result = calculateTotal([{ suit: 'HEARTS', value: 2 }, { suit: 'HEARTS', value: 3 }, { suit: 'HEARTS', value: 4 }]);
        console.log(result);

Answer №3

Using if num return num isn't necessary to retrieve the number in this scenario. The key function at play here is return, which exits the function entirely and passes back the value. To achieve the desired result, a different approach is recommended:

let calculateTotal = function (cards) {
  let total = 0;

  for (let i = 0; i < cards.length; i++) {
    // Instead of directly returning numbers, we evaluate each card's value
    // If a card's value is 1, we add 11 to the total; otherwise, we add the original value
    if (cards[i].value == 1){
      total += 11;
    } else {
      total += cards[i].value;
    }
  }
  // Finally, we return the total sum calculated instead
  return total;
}

Answer №4

Here's a straightforward method that should work:

function calculateTotal(cardObject) {
  let totalScore = 0

  for (let i = 0; i < cardObject.length; i++) {
    switch (cardObject[i].value) {
      case 1: {
        totalScore += 11
        break
      }
      default: {
        totalScore += cardObject[i].value
        break
      }
    }
  }

  return totalScore
}

calculateTotal([{suit:"HEARTS",value:1}]) // 11
calculateTotal([{suit:"HEARTS",value:2},{suit:"HEARTS",value:3},{suit:"HEARTS",value:4}]) // 9

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

Command to set up webpack configuration for watching changes in Angular 2 CLI: ng build --watch

Can I customize the configuration for my ng build --watch command in order to efficiently bundle and minify files on disk each time a modification is made? ...

send additional form elements to the AJAX suggestion box script

** shifted to this location: Numerous similar AJAX suggestion boxes without IDs I enlisted the help of a developer to create a jQuery AJAX suggestion box script some time ago, and it has been working flawlessly. Now, I am striving to understand it better ...

Cleaning a string of word characters in Javascript: a step-by-step guide

I have been working on cleaning strings that were transformed from word text, but I am facing an issue with removing the special character '…' When I click on the "clean" button, the script currently removes all dots and only one special ...

Unable to retrieve context value for authentication requirements

I have implemented a feature in my application where I redirect users to the login page for certain special pages if they are not logged in. The implementation involves using react-router. Here is the code snippet for my RequireAuth component: const Requir ...

Struggling with using flexboxes and creating animated elements

Seeking assistance with animating the search bar on a website project. The animation is functioning, but the search input abruptly moves when the animation starts, as shown in this GIF: https://i.sstatic.net/17sFl.gif I am utilizing jQuery for the animat ...

Having trouble with your computed includes not working in Vue.js? Unsure of how to fix it?

How come when I use "includes" in Vue with my v-model, Vue.js logs an error? However, if I write (.includes("blabla)), everything works fine. What could be the issue? Also, how can I return the entire array if the (if) condition will work? For example, ...

What is the best way to access an external array using ng-repeat in AngularJS?

My dataset consists of 3 separate arrays. "areas": { "default": [ { "area": "Master Bedroom", "uuid": "986e3f42-1797-49ae-b060-181a33b9", "description": "", "new": [ { "value": "986e3f42-1797-49ae-b060-181a3 ...

Passing parameters to $http.get in Angular can be achieved by including them

I am attempting to send a params object to the $http.get() method. My params are structured as follows: var params = { one: value, two: value } I am trying to pass them into my function like this: $http.get('/someUrl', params) .success(fun ...

Jquery click event is functioning for only one specific id, not for both

I'm experiencing an unexpected issue that I can't seem to figure out. I've been working on a webpage where users can download images captured from a webcam or phone camera. Initially, I used an anchor tag with a "download" text that triggere ...

The issue lies with the event.target.name property - it appears to be inconsistent, working at times but failing to read properly at others

Whenever I attempt to click the button, I encounter an error. Interestingly, it seems to work on some occasions and fails on others. import React from 'react'; class Profile extends React.Component{ constructor(){ super(); th ...

Can you explain the role of the faceVertexUV array within the three.js Geometry class?

Currently, I am utilizing three.js to create curved shapes using parametric functions. Within the THREE.js javascript file, there is a function called THREE.ParametricGeometry that continuously adds 2D vectors to the faceVertexUvs array. I am curious abo ...

What could be causing the lack of data for the current user?

I have been attempting to fetch the current user session and display the data in the view, but nothing is appearing. I even checked the database and confirmed an active session with all the necessary information. I attempted logging the user out and starti ...

Adding the number of occurrences to duplicates in a string array using JavaScript

Looking to append a count to duplicate entries within a string array. The array in question contains duplicates, as shown below. var myarray = ["John", "John", "John", "Doe", "Doe", "Smith", "John", "Doe", "Joe"]; The desired output shoul ...

Is your window.location.hash malfunctioning?

I am facing an issue with changing the background color of a <div id="services> when a specific link (index.html#services) is clicked. I have attempted to use the latest jQuery along with the jQuery Color plugin from jQuery Color. The code snippet I ...

Tips for transitioning this JavaScript code into jQuery syntax

Below is my JavaScript code: javascript: function executeCode() { var d = document; try { if (!d.body) throw (0); window.location = 'http://www.example.com/code?u=' + encodeURIComponent(d.location.href); } catch (e) { ...

Angular ngClass and ngIf directives failing to update upon alterations

In my current Angular project, I am working on a functionality where I need to dynamically change a class based on a variable without having to refresh the page. I have experimented with *ngIf/else and [ngClass] directives, which do work, but unfortunatel ...

Once the node modules folder has been received, proceed with installing npm packages

Hello, my name is Jaffer Syed and I'm currently facing a challenge in installing npm packages into my code. Specifically, I am trying to install the num2fraction package from https://www.npmjs.com/package/num2fraction. However, despite watching your n ...

MongoDB Update is only impacting the first element within the array

I have been working on a challenge involving a Mongo updateMany() query. Let me share an example of a document found in my collection: { "CurrentVersion": 3, "EntryHistory": [ { "State": 0, ...

Is there a way to record form choices upon submission?

How can I retrieve selected options from a form upon submission? I have a basic HTML form that triggers a JavaScript function on exit. However, I am unsure of how to capture the chosen option from the <select> element. Please refer to the code snip ...

Sending the value of a react select component from a React.js application to Firebase

To implement dropdown selections that appear upon click, I utilized react-value. Within my code, I hardcoded some static values for the dropdown options as shown below: import React, {useMemo, useState} from "react" import Select from 'react ...