Determine whether there are three or more identical values when comparing two objects in typescript

Hello there, I am in need of some assistance as I am unsure where to begin. Any help would be greatly appreciated. Here are the two objects I have:

const Questions = {
 five: "c"
 four: "c"
 one: "a"
 three: "a"
 two: "a"
};

And I also have this object:

const Answers = {
 five: "a"
 four: "a"
 one: "a"
 three: "a"
 two: "a"
};

My objective is to compare these two objects and determine if there are 3 or more correct matches. Based on the comparison result, I need to display a different message. I have attempted comparing the two objects like this:

JSON.stringify(Questions) === JSON.stringify(Answers);

However, this only returns true or false. I also tried to return only the corrected answers with the following code snippet:

checkCorrectAnswers(obj1: any, obj2: any): any {
    const keys1 = [];
    const values1 = [];
    Object.keys(obj1).forEach((element) => {
      keys1.push(element);
    });
    Object.values(obj1).forEach((element) => {
      values1.push(element);
    });
    // More code goes here...
}

I appreciate any further guidance or solutions provided. Thank you.

Answer №1

To efficiently check for answers, you can loop over the questions like this:

const Answers = {
 five: "a",
 four: "a",
 one: "a",
 three: "a",
 two: "a"
};

const Questions = {
 five: "c",
 four: "c",
 one: "a",
 three: "a",
 two: "a"
};

const isPass = (passingScore) => {
  let score = 0

  for (const questionKey in Questions) {
    const questionValue = Questions[questionKey];
    const answerValue = Answers[questionKey]

    const isCorrect = answerValue === questionValue

    if (!answerValue) {
      continue
    }

    if (isCorrect) {
      score++
    }
  }

  return score >= passingScore
}

The advantage of this approach is that it requires only a single loop to complete.

Answer №2

If you're looking to find the accurate responses, here's a simple method you can utilize.

const Questions = {five:"c",four:"c",one:"a",three:"a",two:"a"};
const Answers = {five:"a",four:"a",one:"a",three:"a",two:"a"};

const keys = Object.keys(Questions);
const correctAnsCount = keys.reduce((accumulator, currentKey) => {
  if (Questions[currentKey] === Answers[currentKey]) accumulator++;
  
  return accumulator;
}, 0);

console.log(correctAnsCount);

Answer №3

const Questions = {five: "c", four: "c", one: "a", three: "a", two: "a"};
const Answers = {five: "a", four: "a", one: "a", three: "a", two: "a"};
correctAnswers = Object.fromEntries(Object.entries(Answers).filter(([k, v]) => Questions[k] === v));
incorrectAnswers = Object.fromEntries(Object.entries(Answers).filter(([k, v]) => Questions[k] !== v));
console.log("Correct answers:", correctAnswers);
console.log("Incorrect answers:", incorrectAnswers);
console.log("Passed:", Object.keys(correctAnswers).length >= 3);

Result

Correct answers: { one: 'a', three: 'a', two: 'a' }
Incorrect answers: { five: 'a', four: 'a' }
Passed: true

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

Implementing Conditional Class Addition in React.js

Currently, I am utilizing Reactjs (Nextjs) to work on my project. The project consists of a "Home page" as well as several other pages such as about and services. To integrate these pages in Nextjs, I created "_document.js". However, I have encountered a ...

Wave Filter in SVG

While attempting to create a fisheye-esque filter in my SVG, I came across this interesting codepen example: http://codepen.io/johanberonius/pen/RopjYW The effect works well, but I would like it to be a bit more pronounced. Unfortunately, I am unable to m ...

Exploring the versatility of HTTP actions in Express: Using GET and

Currently, I am setting up a server through express. While everything is running smoothly with my project, I have a small query that is not related to the project itself. My confusion lies in the requirement to use the GET method when, in my opinion, usi ...

How to verify if an object is empty in an AngularJS expression

I need to display either a Login or Logout button based on the value of a $rootScope variable. Currently, only the Logout button is showing up in the li tag below. I have specific actions that should occur after certain events: After Logging In:- $root ...

Limiting the display to only a portion of the document in Monaco Editor

Is there a way to display only a specific portion of a document, or in the case of Monaco, a model, while still maintaining intellisense for the entire document? I am looking to enable users to edit only certain sections of a document, yet still have acce ...

The Google Geo Charts fail to load when initiated by Ajax requests

My goal is to use ajax to load an external HTML page that includes the following code: <script type='text/javascript' src='https://www.google.com/jsapi'></script> <script type='text/javascript'> function ...

When using Vuejs + Laravel to make an Ajax request, only the most recent information entered into the view is submitted

Can someone guide me on implementing a basic ajax request using Vue with my Laravel backend? I have a boolean field called completed in a table named courses. In the view, users can see all assigned courses and toggle their completion status by pressing a ...

When trying to use TypeScript with next.js, encountering an unexpected token `?` error is not

Having an issue with next.js, the command npm run dev keeps failing due to a syntax error related to an optional property in a tsx file: Syntax error: Unexpected token 44 | 45 | type State<T_HT> = { > 46 | ghostHighlight: ?{ | ...

What is the best way to conceal an HTML element on a particular page that is already styled as (visibility: visible), but only if its child has a specific class assigned to it?

I have a grid of content and posts displayed on multiple webpages. Users can select specific items from the grid to navigate to more detailed information on another page. Each webpage has its own grid which I want to filter based on a specific class. The ...

Creating an Efficient Lazy Loading HTML Page with jQuery

I've been looking to create a page that loads content only as the user scrolls to that specific section, similar to the way Pinterest website functions. Does anyone have suggestions on how to design and implement this feature, or know of any plugins ...

Utilizing SEO and incorporating special characters like !# in a website's URL

I came across an interesting concept about designing a website that utilizes AJAX to load each page section without compromising SEO. It involved incorporating !# in the URL, similar to the approach adopted by Twitter. However, I've been unable to loc ...

Combining Vitest with FastifyAutoload resulted in a FastifyError: The plugin provided must either be a function or a promise, but instead, an 'object' was received

My application built on Fastify ("fastify": "^4.26.0") operates smoothly under normal conditions with no issues. However, when trying to incorporate unit testing using Vitest, every test fails despite their simplicity. Upon troubleshoot ...

Run the .map() method at regular intervals of 'x' seconds

I have a certain function in mind: function fetchDesign (items) { items.map(item => item.classList.add('selected')) // additional code here } Is there a way to trigger item.classList.add('selected') every 2 seconds, while ensu ...

Is there a way to identify the Xpath after clicking a button that adds a row to the JQGrid?

Seeking the Xpath for the Row that was added upon clicking a button. Need to click on the datepicker in the first row and first column to select a date. How can I locate the Xpath for this date picker element? See my code snippet below `<table ...

Creating a personalized script in ReactJS: A step-by-step guide

If I have already built a component with Google Chart in ReactJS, and I want to implement a feature that allows the Legend to show/hide data using a JavaScript script provided here, how and where should I integrate this code to work with my chart? Here is ...

Sluggish animation performance in threejs when using requestAnimationFrame within a class

Experiencing choppy animation on the JSFiddle? When trying to move your mouse or interact with the content, you may have come across issues with the classing related to requestAnimationFrame(this.animation). Initially, it didn't work as expected, but ...

Display or conceal various content within div elements using multiple buttons

I have a set of 5 image buttons, each meant to trigger different content within a div. When the page loads, there should be default content displayed in the div that gets replaced by the content of the button clicked. The previously displayed content shoul ...

Encountering an issue while attempting to send an image through JavaScript, jQuery, and PHP

I'm currently attempting to upload an image using JavaScript/jQuery, but I am unsure of how to retrieve the image in order to send it to a server (PHP). I have a form containing all the necessary information that I want to save in MySQL, and I use jQu ...

Creating client side scripts for an ajax call to generate a Json object is simple once you understand the basics

Typically, when I make ajax calls, I request pure HTML. However, for various reasons, I require guidance on constructing a table (let's say of individuals and their information) when receiving a Json object. While I am capable of creating a table in J ...

Selecting options on hover, either A or B at the least

I need a jQuery selector to handle an 'either' scenario. Specifically, I have a dropdown menu and want it to stay open when the user hovers over either of two elements. Either when they hover over the button or when they leave the popped-out men ...