2

Probably making a silly mistake, but i can't seem to figure this one out.

Based on an existing array of strings, i want to check if they exist as an object value within my array of objects. If true, push them into the new array with a true value, if false, also push them in the new array, but with a false value.

Example of my code so far:

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}
]

This pushes objects to my new array, and it all works fine! Problem is when i want to add the false ones. I'm trying to do this as followed:

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}
]

// would expect it to be: 
[
  {id:12, author: 'A', correct: true}, 
  {id:4, author: 'B', correct: false}, 
  {id:16, author: 'C', correct: true}
]

What am i missing here?

0

2 Answers 2

1

I think that you need to be looping through quotes rather than answers, and then seeing if there's a matching value for the quote in the answers.

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

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

console.log(res);

Sign up to request clarification or add additional context in comments.

Comments

0

Here is an answer for a minimal amount of loops.

  1. Create an object from the answer array - {'value': true}, using reduce.
  2. Looping through the answers, while checking up if the answer is correct in the object that is created in point 1).

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.