Home > Enterprise >  Filter nested objects javascript
Filter nested objects javascript

Time:09-27

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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

  • Related