Intermediate javascript, isTheDinnerVegan() stuck

Hey guys,

I am getting stuck at this exercise “Intermediate javascript, isTheDinnerVegan()

I get the solution right but the exercise won’t accept it.

// Code challenges: Intermediate Javascript, isThe DinnerVegan() 

// My code:

const isTheDinnerVegan = (meal) => {
  let isVegan = [ ]; // define isVegan as an empty array to be used later
  for (let i=0 ; i < meal.length; i++) { // iterate past all objects in the array meal, if a meal has multiple courses, no problem.
    if (meal[i].source === 'plant') { // check if a key value === 'plant'
      isVegan.push(true); // pushes true to an array that lists every course
    } else {
      isVegan.push(false); // dito but false
    }
  }
  return isVegan.every(function (x) { x === true}); // checks if all items are true / vegan
};

// Check my code

const dinner = [{name: 'hamburger', source: 'meat'}, {name: 'cheese', source: 'dairy'}, {name: 'ketchup', source:'plant'}, {name: 'bun', source: 'plant'}, {name: 'dessert twinkies', source:'unknown'}];

console.log(isTheDinnerVegan(dinner))
// Should print false, and it does!
1 Like

from the every method documentation:

true if the callback function returns a truthy value for every array element; otherwise, false .

your function doesn’t return anything, the absence from a return value is not truthy, thus its false

2 Likes

Hmm you are right, even if I enter a meal with plant only sources it returns a false. Will look into that, thx!

1 Like

yes, and it has to do with .every.

The function you pass as argument, doesn’t return anything, thus we get undefined, which is false.

2 Likes
return isVegan.every(function (x) { return x === true});

Solved it! Thx.

1 Like

if you are going to use high order functions (like every), why not call every directly on meal?

now you loop twice, is that really needed?

2 Likes

My idea was to also be able to log which meal is not Vegan.

But I am eager to know how I can do this with less code. Only started looking into Javascript earlier this month ;).

1 Like

I first tried solving the exercise by implementing a while loop that stopped at the first instance of false and then returned a false, but somehow that wasn’t enough to solve the exercise either. Perhaps I did something wrong there too.

Could you do:

meal.every(function (x) { return x.source === 'plant'})

or something like that?

1 Like

yes, you can. Using es6 you can shorten it even more:

return meal.every(x => x.source === 'plant')

this sounds like a very realistic way to solve the problem. that should work. Just be careful to return true outside/after the loop.

2 Likes

Thx for the info ;).

1 Like

hi this worked for me:
const isTheDinnerVegan = (value) => {
const val = value.every(function (i) {return i.source ===‘plant’})
return val;
}

1 Like