0

I can't get to solve this exercise

The called function receives as an argument an object 'guests', in the object we have objects that represent the guests at a party where they all have an "age" property. You must return the number of guests who are under 18

In the following example it should return 2

I tried to solve it in several ways, at the moment it goes like this:

function howManyMinors(guest) {
    let guests = {
    Luna: {age: 25},
    Sebastian: {age: 7},
    Mark: {age: 34},
    Nick: {age: 15}
    };
      
    var minors = 0;
    for(element in guests) {
        if(Object.values(guests) <= 18) {
            minors ++;
        }
    }
    return minors;
}
1
  • Don't use guests when you mean guests[element]. And don't use Object.values when you just need .age. Commented Sep 24, 2022 at 19:41

3 Answers 3

0

You aren't using the incoming parameter. There is no need to define an internal object inside of the function.

To compute the number of guests who are under 18, I would do something like:

function howManyMinors(guests) {
let minors = 0;
  for (const guest of Object.values(guests)) {
    if (guest.age < 18) minors++;
  }
  return minors;
}

howManyMinors({
    Luna: {age: 25},
    Sebastian: {age: 7},
    Mark: {age: 34},
    Nick: {age: 15}
}); // 2
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much I had been trying to solve it for a long time and you did it in a simple and fast way I had already tried something similar but had problems accessing the value of the object. Now everything is clear to me
0

In this specific case, there is a better tool for the job which is Array#filter:

function howManyMinors(guests) {
  return Object.values(guests).filter(guest => guest.age < 18).length;
}
const guests ={ Luna: { age: 25 }, Sebastian: { age: 7 }, Mark: { age: 34 }, Nick: { age: 15 } }
console.log(howManyMinors(guests)) // 2

Comments

0

The code you attached is not clear. For example, you don't use the guest argument at all. If I understand you right, you have an object that each property of it represents a guest. Each guest is an object with an age property and your job is to count the guests with age <= 18.

If I understood you correctly, you can do something like this:

const guests = {Luna: {age: 25},
    Sebastian: {age: 7},
    Mark: {age: 34},
    Nick: {age: 15}};

const count = Object.values(guests).reduce((count, value) => value.age <= 18 ? count + 1 : count, 0);

console.log(count);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.