Selecting specific elements from an array in JavaScript can be achieved by using various methods and techniques

Currently working on a quiz incentive system where users earn rewards based on the number of correct answers they input. The example array below shows the possible range of correct answers:

var rightAnswers = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];

if (rightAnswers.selectAny(3)) {user receives a star}
else if (rightAnswers.selectAny(6)) {user earns 2 stars}
else if (rightAnswers.selectAny(9) {user is awarded with 3 stars}

I am currently stuck on finding an alternative to my pseudo code method "selectAny()", any suggestions would be greatly appreciated.

Answer №1

It seems like you're not looking for a chooseAny function; what you really need is a way to calculate the number of correct answers from a given set of answers and an answerKey.

The provided getTotalCorrect function uses a for-loop and identity comparison to achieve this, while the getStars function can be used to determine the star rating based on the calculated score.

var answerKey = ['a', 'b', 'c', 'd', 'e', 'f', 'g']

function getTotalCorrect (answers, answerKey) {
  for (var correct = 0, i = 0; i < answerKey.length; i++) {
    if (answers[i] === answerKey[i]) correct++
  }
  return correct
}

function getStars (totalCorrect) {
   return (totalCorrect / 3) | 0
}

var totalCorrect = getTotalCorrect(['a', 'a', 'c', 'c', 'e', 'e', 'e'], answerKey)
console.log(totalCorrect) //=> 3

var stars = getStars(totalCorrect)
console.log(stars) //=> 1

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

Having issues with Element UI sorting values in a table

I've been attempting to create a basic sorting function, but it doesn't seem to be functioning correctly. var Main = { data() { return { tableData: [{ value: '1.799,37', name: 'Tom 3' }, { ...

To display a pattern with a series of alternating addition and subtraction operators, starting from -1 and ending at n, use JavaScript to iterate through the numbers and implement the pattern -1+

I've been struggling to locate the values despite numerous attempts. What steps can I take to resolve this issue? Below is my code snippet: var numVal = prompt(""); for (var i = 1; i <= numVal; i++) { if (i % 2 !== 0) { console.log("-"); ...

The value of the checkbox model in AngularJS is not defined

I'm encountering an issue where I am trying to send the value of a checkbox from my model to the server. Since the checkbox has not been interacted with on the form, Angular does not assign it a value and returns undefined when I request the value. B ...

Is it possible to utilize relational operators to determine if a pointer is pointing to an element within an array?

Is it possible to determine if a specific pointer points to an object within an array, within its specified bounds? template <typename T> bool points_within_array(T* p, T* begin, T* end) { return begin <= p && p < end; } Are the p ...

Is there a way to create a navigation menu that highlights as we scroll down the page?

Check out this example of what I am looking for. https://i.stack.imgur.com/fdzvZ.png If you scroll, you will notice that the left menu highlights. Sub-menus will extend when the corresponding menu is highlighted and collapse when other menus are highlig ...

Is it accurate that JavascriptResult displays javascript on the page in a string format?

I am new to .NET MVC and have been experimenting with different return types in MVC. However, I am having trouble getting the JavaScriptResult to work. In my controller, I have the following code: public ActionResult DoSomething() { string s = ...

JavaScript AJAX function is returning an undefined value rather than a boolean true or false

My AJAX call function in jQuery has a complete section with the following code: complete: function(XMLHttpRequest, textStatus) { if(textStatus == "success") { return(true); } else { return(false); } } However, when ...

I am attempting to retrieve JSON data in JavaScript but am seeing a null response in the action class

Having an issue with JSON data being sent through AJAX from the client side. The data is showing as null inside my action class. Here is the JSON string: {"data":[{"id":"","col":1,"row":1,"size_x":1,"size_y":1}, {"id":"","col":1,"row":2,"size_x" ...

Transform a text string into JSON format using Javascript

I need help converting a text string to JSON format using JavaScript. The text string is as follows: workingtable;AB8C;book_id;7541; I want to convert it into JSON format like this: {"workingtable":"AB8C","book_id":"7541"} Is there a specific JSON funct ...

Is there a way for me to locate the ownerID?

I have a simple task that I need to complete My goal is for the user to be identified using my token when creating a post This is how the create function looks like: exports.create = async (req, res) => { const user = req.token; const users = awai ...

When making a variable call outside of a subscriber function, the returned value is 'undefined'

I find myself in a situation where I have to assign a value to a variable inside a subscriber function in Angular. The issue is that the variable returns 'undefined' when called outside of the Subscribe function. Here's what I'm encount ...

Angular promise not accurately retrieving data from JSON API

Last Updated: 02/12/2015 After reading through the comments, I discovered that the issue stemmed from an Angular module modifying the object. By using toJSON, I was able to pinpoint the problem. I recently encountered a perplexing issue. I have a service ...

Experimenting with Chai in JavaScript to test an incorrect argument

Background: I recently delved into JavaScript and have been experimenting with it. It's possible that my question may sound silly, but I am eager to learn. I have developed a function called `getDayOfTheWeekFromDate` which returns the day of the week ...

The error message "TypeError: Cannot read properties of undefined (reading 'prototype')" is encountered in Next.js 13 when trying to access the prototype of an

I tried to integrate the downshift library into my project. However, when I attempted to use a basic example from the GitHub repository here, I encountered an error. Current versions: Next.js: 13.2.4 React: 18.2.0 Upon further investigation, it seems lik ...

The length of the Array is accurate

Hey there! I'm facing an interesting challenge in my second semester of object oriented programming. For my first project in my intro to java course, I need to create a Date class that calculates the days elapsed from January 1st of the year. I have t ...

What is the best method in JavaScript to create three different shades of a color?

My sass function generates lighter and darker versions of a base color, here is the code snippet: $colors: ( betpawa-green: #107A3D, lime-green: #8DC63F, yellow: #FBCD00, ); @mixin color-generator { @each $name, $hex in $colors { &-#{$nam ...

Another option instead of using useCallback

Forgive me if this is a novice inquiry, but I am still learning JavaScript and React. I recently discovered the necessity of utilizing useCallback to wrap callback functions in order to prevent them from being recreated constantly when used within a fun ...

Interactive Div Updates Dropdown Selections Automatically

// function to add set of elements var ed = 1; function new_server() { ed++; var newDiv = $('#server div:first').clone(); newDiv.attr('id', ed); var delLink = '<a class="btn btn-danger" style="text-align:right;m ...

What is the best way to change a date written in the format 'xxth Mar XXXX' into 'DD/MM/YY' format?

Currently, I am working on a React project and facing an issue with the date output format. The date is being displayed in the format of xxth Mar XXXX, but I need it in DD/MM/YY format. For example, if the date is shown as 18th Mar 2021, I want it to be d ...

What is the best way to pass a prop into the <router-link>?

If I replace this {{ name }}, the result is "campaigns" Now, I want to use that in my link <router-link :to="'/' + '123' + '/' + item.id"> {{ item.name }}</router-link> I attempted to substitute '1 ...