Create a fresh array of items using an array and an object that already exists

Seems like I'm missing something obvious, but I can't seem to crack this one.

I have an existing array of strings and a separate array of objects. My goal is to check if the strings exist as values in the objects within my array of objects. If they do, I want to push them into a new array with a true value. If not, I still want to push them into the new array, but with a false value.

Here's a snippet of my code:

const answers = [12, 3, 16]
const quotes = [
{ id: 12, author: 'A'}, 
{ id: 4, author: 'B'}, 
{ id: 16, author: 'C'},  
]
let checkedQuotes = [];

answers.forEach((answer) => {
   ​quotes.find((quote) => (quote.id === answer
       ​&& checkedQuotes.push({
         ​id: quote.id,
         ​author: quote.author,
         ​correct: true,
       ​})
   ​));
 ​});

returns => [
  {id:12, author: 'A', correct: true}, 
  {id:16, author: 'C', correct: true}
]

The code above successfully pushes the correct objects to my new array. However, I encounter issues when trying to handle the false ones. I've attempted the following approach:

answers.forEach((answer) => {
    quotes.find((quote) => (quote.id === answer
      ? checkedQuotes.push({
        id: quote.id,
        author: quote.author,
        correct: true,
      })
      : checkedQuotes.push({
        id: quote.id,
        author: quote.author,
        correct: false,
      })
    ));
  });

returns => [
  {id:12, author: 'A', correct: true}, 
  {id:12, author: 'A', correct: false}, 
  {id:12, author: 'A', correct: false}
]

// The expected output should be: 
[
  {id:12, author: 'A', correct: true}, 
  {id:4, author: 'B', correct: false}, 
  {id:16, author: 'C', correct: true}
]

What am I overlooking here?

Answer №1

Consider adjusting your approach to iterate over quotes instead of answers, and then check for a corresponding value in the answers.

const answers = [10, 6, 20];
const quotes = [
  { id: 10, author: 'X' }, 
  { id: 3, author: 'Y' }, 
  { id: 20, author: 'Z' },  
];

const result = quotes.map(
  (quote) => ({ ...quote, correct: answers.includes(quote.id) })
);

console.log(result);

Answer №2

Provided here is a solution that minimizes the use of loops.

  1. Utilize the reduce function to create an object from the answer array with the structure {'value': true}.
  2. Iterate through the answers, cross-referencing them with the object created in step 1) to determine correctness.

const answers = [12, 3, 16]
const quotes = [
{ id: 12, author: 'A'}, 
{ id: 4, author: 'B'}, 
{ id: 16, author: 'C'},  
]

const answersObj = answers.reduce(function(obj, answer) {
  obj[answer] = true;
  return obj;
}, {});

for (quote of quotes) {
  quote['correct'] = answersObj[quote.id] || false;
}

console.log(quotes)

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

"Utilizing HTML for mouse click events and linking to

Here's a link I am working with. <a href="board.php?id={$id}" onclick="javascript:parent.$.fancybox.open({href : 'board.php?id={$id}', type: 'ajax'});"> In situations where JavaScript is disabled, the browser will use the h ...

JavaScript node_modules import issue

I've been grappling with this issue for quite some time now. The problem lies in the malfunctioning of imports, and I cannot seem to pinpoint the exact reason behind it. Let me provide you with a few instances: In my index.html file, which is complet ...

`<picture> contains the main image``

Is it possible to access the currently displayed source of a <picture> element in JavaScript without relying on viewport width or pixel density? Looking for a method similar to <select>:selected If anyone has insights on this, please share! ...

What other choices are available for the Angular ui-select2 directive?

Within the Angular select2 controller below: <select ui-select2 id="projectListSelection" data-placeholder="Select a Project ..." ng-model="selectedProject"> @*ng-options="project.WebsiteName for project in projectList"*@ ...

How can Angular incorporate an external JavaScript library?

I'm currently facing an issue with importing libraries like popper, jquery, and chart.js into my Angular project. After downloading them through the CLI, I made sure to reference them in both my index.html and angular.json files. index.html <hea ...

Sending dynamic data through AJAX to a CodeIgniter controller is a common task that allows for seamless

Can anyone help me with retrieving data from a looping form in CodeIgniter? The form works fine, but I'm struggling to fetch the looping data in the controller. Here's my view (form): <form action="#" id="ap_data"> <div class="table-r ...

What could be the reason behind this vuejs v-for loop causing an undefined error?

As a beginner in Vue, I am trying to understand the basics by creating an example that displays a list of numbers which are properties of vue data objects. However, when I attempt to use the v-for directive in a loop, I encounter an error message: TypeErr ...

Is there a way for my element to fill the entire screen and prevent any scrolling from occurring?

I am looking to ensure that my children's div occupies the remaining space on the screen and prevent scrolling. Since I am utilizing PanZoom, I need the children's div to always fill 100% of the screen. <div class="parent"> &l ...

Unable to make colors appear in HTML5 canvas using .fillStyle

Trying my hand at canvas for the first time to create a game. I have an image displaying, but strangely the fillStyle method doesn't seem to be working as expected (the canvas background remains white in Google Chrome). Just a note that in my code, t ...

Is there a way to fill an array with palindromes by utilizing a loop?

Seeking help on this platform for the first time, and also attending my initial Java class ever. I am facing a roadblock while attempting to fill an array with palindromes. Despite trying everything, I have not been successful so far. Can someone please gu ...

consolidate totals and save them in an array

After performing a multiplication operation on the 2D array with another array, the following results were obtained: 76,0,38,7,32,0,16,18,32,0,16,18,0,0,0,19,16,0,8,23,76,0,38,25 I now wish to add values in pairs and store them in an array called results ...

VueJS - Vuefire - Unexpected Error: document.onSnapshot is not a valid function

I'm currently working on integrating Vuefire into my project. I have been following the instructions provided on the Vuefire website, but I am encountering an error. db.js: import firebase from 'firebase/app' import 'firebase/firestore ...

Getting a vnode from a DOM element in Vue 3.0: A Step-by-Step Guide

My question pertains to obtaining a vnode through accessing the DOM using document.getElementById(id). How can I accomplish this? ...

Alter the Default Visibility on an HTML Page from Visible to Hidden with JavaScript

I found this code snippet on a website and made some modifications. On my webpage, I have implemented links that toggle the visibility of hidden text. The functionality is working fine, but the issue is that the hidden text is initially visible when the p ...

How can I ensure that Redux-saga waits for API calls to resolve instead of returning promises continuously? Is there a way to make "yield call" wait for API calls to complete?

Where I'm initiating the API request: function fetchCharacter(value){ return axios.get(`https://www.breakingbadapi.com/api/characters?name=${value}`) .then(res=>{ console.log(res.data) }) .cat ...

JavaScript zooming library designed to provide interactive zoom functionality similar to Google Maps

Seeking guidance on creating a web app centered around a zooming principle (ZUI). Currently researching frameworks or starting points, similar to OpenZoom but in javascript. Any recommendations appreciated! ...

Click on a React component to receive its property

Hey there! I'm currently in the process of developing an app that allows users to search for books and organize them onto specific shelves with just a click. Right now, users can type a query and see multiple results displayed on the screen. My goal i ...

Writing the success function for a jQuery ajax call involves defining the actions to be taken once

Embarking on my journey to learn jQuery and web development, I am faced with the task of sending user input (username and password through a submit button) to a PHP page using .ajax and success function. Below is the HTML form code: <form id="form1"&g ...

The specified function 'isFakeTouchstartFromScreenReader' could not be located within the '@angular/cdk/a11y' library

I encountered the following errors unexpectedly while working on my Angular 11 project: Error: ./node_modules/@angular/material/fesm2015/core.js 1091:45-77 "export 'isFakeTouchstartFromScreenReader' was not found in '@angular/cdk/a11y&a ...

Issues arise when trying to render text within Javascript as "NOTICE", however PHP is able to display it seamlessly without any hiccups

PHP uses metadata from image files to create text and stores it in a variable with the same name as the IMG source. No issues there. JavaScript is responsible for displaying the gallery, allowing users to scroll and enlarge images. While enlarging an imag ...