Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Filter nested objects javascript

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading