Is there a method to verify the presence of an object within an array, and if it is not found, add it to the array?

In this quiz, I am collecting question numbers and answers to store in an array. The goal is to replace old answers with new ones if a person changes their response on the quiz. If a question hasn't been answered yet, it should be added to the array at the appropriate index location.

let questions = [];


function get_id(xd,jf){

    let question = (xd.parentNode.id);
    let question_num = document.getElementById(question).getAttribute("value");
    let number = document.getElementById(jf).getAttribute("value");
    let new_answer = {Question:question_num, Answer:number};

    questions.push(new_answer);

    let found = questions.includes(new_answer);

    console.log(found);

    if (found == false) {
        questions.push(new_answer);

    };

    // if (questions.some... " i couldn't understand how to use the some method"

    //for (i = 0; i < questions.length; i++) { "and was thinking about using a for loop somehow."

    console.log(questions);

};

I attempted to use the includes method to compare new and old answers, but it always returned true regardless of actual comparison results.

Below are other ideas I tried, but being new to programming, I'm unsure of the approach.

Here's the HTML structure of a single question:

<div class="row" id="question_1" value="0">
  <div class="col-sm-2">
    <div class="A">
      how are you?
    </div>
  </div>
  <div class="col-sm-2" id="answer5" onclick="get_id(this, id)" value="10">
    <button id="answer5" value="10">
      5
    </button>
  </div>
  <div class="col-sm-2" id="answer4" onclick="get_id(this, id)" value="8">
    <button id="answer4" value="8">
      4
    </button>
  </div>
  <div class="col-sm-2" id="answer3" onclick="get_id(this, id)" value="5">
    <button id="answer3" value="5">
      3
    </button>
  </div>
  <div class="col-sm-2" id="answer2" onclick="get_id(this, id)" value="2">
    <button id="answer2" value="2">
      2
    </button>
  </div>
  <div class="col-sm-2" id="answer1" onclick="get_id(this, id)" value="0">
    <button id="answer1" value="0">
      1
    </button>
  </div>
</div>

I haven't utilized button properties beyond styling them.

Answer №1

You are overcomplicating the issue.

It's worth noting that the array index and question numbers match, so there's no need to search for an answer in the array. It's either already in place or not.

The correct method to insert an answer into the array is not using push, as it adds to the end of the array. Instead, you should place the answer in its correct array position like this:

questions[question_num] = {Question: question_num, Answer: value);

// JavaScript code here

Answer №2

In my opinion, the proper method to accomplish this is as follows:

  1. Filter out the questions that have already been answered
  2. If the question has not been answered yet, keep it in the list of questions
  3. Add the new answer to the list of questions.

Here is the code snippet:

questions = questions.filter(q => q.question_num !== new_answer.question_num);

questions.push(new_answer);

Answer №3

Here's a neat way to utilize Array.findIndex. It provides a much cleaner solution:

let questions = [];


function get_id(xd,jf){

    let question = (xd.parentNode.id);
    let question_num = document.getElementById(question).getAttribute("value");
    let number = document.getElementById(jf).getAttribute("value");
    let new_answer = {Question:question_num, Answer:number};

    const found = questions.findIndex(v => v.Question === question_num);
    if(found === -1){
      questions.push(new_answer);
      console.log("new question answered");
      console.log(questions);
      return;
    }
  
    questions[found].Answer = number;
    console.log("new question updated");
    console.log(questions);

};

Feel free to check it out on CodePen :)

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 HTML form submission button fails to submit the form and instead just refreshes the page

I'm struggling to get the save button working on my Chrome Extension settings page. The .click() event doesn't seem to be activating at all. I've included my code below. Should I use the commented out button instead (see below)? HTML <! ...

When using node.js with SendGrid to send emails to multiple recipients and adding substitution, a blank value

I encountered an issue when sending emails to multiple recipients using SendGrid. I noticed that the substitution values were blank. Technologies Node.js SendGrid (v2) ==== My Sample Code (Node.js) ==== const SENDGRID_API_KEY = 'KEY' const s ...

Discovering nearby intersections within 2 sets of arrays

Imagine having these two arrays: var a = [126, 619, 4192, 753, 901]; var b = [413, 628, 131, 3563, 19]; Is there a way to identify elements in both arrays that are close to each other by a certain percentage? Let's say we have the following functio ...

"Encountering a Node.js error while trying to open an image for the second

My goal is to use Node to take a screenshot of the user's screen on all displays and save everything in a single image. Everything works fine when I call it for the first time, but if I try to call it a second time without restarting the server, an er ...

What is the process for adjusting the code to manage the labels of specific buttons?

There is a code $("button").click(function() { var btn = this; if (btn.loaded) { $(btn).prev("div").html(btn.originalContent); btn.loaded = false; $(btn).text('Get Dynamic chart'); } else { btn.originalConte ...

Retrieving data from Ajax and passing it to PHP

I am currently facing an issue with my Ajax code. When I try to access a textfield variable in PHP after alerting the value successfully, I receive an error stating Undefined index. Javascript Code <SCRIPT> function sendData(UserID) { var name = en ...

Is there a way to eliminate a particular item from a Formdata object array?

Looking to access a specific item in formData to remove it from the Object and retrieve its name value. I attempted formdata.delete through the console, but it removed the entire object with undefined returns. What I want is to remove a single item that c ...

What are the steps to integrate openjphjs with next.js?

I am working on a project with Next.js and need to utilize openjphjs for decoding HTJ2K pixel data. In order to incorporate openjphjs, I have included both openjphjs.js and openjphjs.wasm in a specific folder within the project structure. To address an e ...

The functionality of Angular animate becomes compromised when there is a conflict between predefined CSS states and transition states

Explore this example CSS code: /* animations at the start */ .error-animation.ng-enter { -webkit-transition: 0.5s linear all; transition: 0.5s linear all; opacity: 0; } ...

Having trouble retrieving all JSON properties

I am facing an issue with my json structure where I am unable to access certain properties. I can only access the main properties like type, properties, and so on within that hierarchy level. However, I cannot seem to access icon, iconURL, or title. The da ...

Adding two double arrays together using AVX vectorization technique

I'm looking for a way to add the elements of two double arrays together and store the result in a third array. Currently, I have the following simplified function: void add( double* result, const double* a, const double* b, size_t size) { memcpy( ...

The push() function for Angular $scope is not defined

Below is the HTML code snippet provided: <input ng-blur="CheckUser()" name="username" ng-model="RegisterFormData.username" class="form-control"/>{{ a.check_username_result }} I have assigned the controller ...

mdButton causing multidir error

I attempted to integrate <md-button> from angular-material, however, I encountered some difficulties. Specifically, I kept receiving a [$compile:multidir] error. More details about the error can be found in this Error link. If you're interested, ...

Streaming data from the server to a Three.JS 3D cube model via Server Sent Events (SSE) is experiencing sluggish performance

In my current project, I am working on developing a client-server application that involves taking accelerometer data via SSE and passing it to a three.js model for rendering in the browser. Specifically, the application's goal is to visualize real-ti ...

Are the keys in Postgresql JSON displayed with underscores separating the letters?

I'm currently developing a web application that communicates with a Rails API on top of a Postgres database. As part of my data storage strategy, I am utilizing the jsonb datatype in Postgres to store certain data in JSON format. To adhere to a consis ...

What is an alternative way to replicate the functionality of jQuery's remove() method using only vanilla JavaScript?

Here is the line of code I have: $('.js-cover-menu-dropdown > li > ul').remove(); This code removes all ul elements from the lis within .js-cover-menu-dropdown. I am curious about how I could rewrite this using plain JavaScript. ...

What are the best practices for utilizing the createPages API to generate pages through programming?

In the process of developing my portfolio, I envisioned having distinct tabs for my blogs and projects. My goal was to dynamically generate pages for each item in these tabs. Following the Gatsby official tutorials, I successfully implemented this functio ...

What is the best way to create a new object in a Vue component with optimal efficiency?

Currently, I am working on initializing a map that would be utilized in my calculatePrice function. calculatePrice(key) { let prices = new Map({ 0: 17, 1: 19, 2: 24, 3: 27, 4: 30, 5: 46, 6: 50 ...

Learn how to store the outcomes of an HTTP operation within array.map() in JavaScript

Having read numerous articles, I am a complete beginner when it comes to async programming and struggling to grasp its concepts. My goal is to map a filtered array of objects and return the result of a function (an amount) to set as the value of pmtdue. De ...

Tips for optimizing content loading without a full page refresh using Ajax

As a newcomer to the world of coding, I am currently working as a beginner webdev specialist. My boss has tasked me with enhancing the website in a way that only the inner content is reloaded when the page is refreshed while keeping the top panel, side bar ...