Home > Enterprise >  Stuck on array objects while needing to return true or false JavaScript
Stuck on array objects while needing to return true or false JavaScript

Time:09-16

I've just started learning about arrays and functions today and would like some help on this following challenge, please. The array is passed in when calling the function.

If there is at least one film where the wonOscar property is false then the function should return false overall. Otherwise, if every film has won an oscar then the function should return true.

What I have so far;

function Winners(films) {
    return films.every(element => element === false);
  }

Example array of films will look as follows:

Winners([
    {
        title: "Fake Movie1", wonOscar: true
    },
    {
        title: "Fake Movie2", wonOscar: true
    },
    {
        title: "Fake Movie3", wonOscar: false
    }
    {
        title: "Fake Movie4", wonOscar: true
    }
]
);
// should return false

Can you please give me a working example and break it down for me how it works? Many thanks!

CodePudding user response:

You need to use property instead of entire object

Instead of doing element === false, you need to check for element.wonOscar.

Also, if you do element.wonOscar === false and you have a false element, it will yield true. You need to yield false in this case.

When you use predicates, try to make the return expression in a way that satisfies your truth condition. In your case, its all films having won oscar. So it should be film.wonOscar === true. Since its already a boolean value, you can even return film.wonOscar directly as it will yield same result

Example:

function Winners(films) {
  return films.every(film => film.wonOscar);
}


console.log(Winners([{
    title: "Fake Movie1",
    wonOscar: true
  },
  {
    title: "Fake Movie2",
    wonOscar: true
  },
  {
    title: "Fake Movie3",
    wonOscar: false
  }, {
    title: "Fake Movie4",
    wonOscar: true
  }
]));

  • Related