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

function that filter an array using if condition and cycles

I’m trying to learn something about arrays and I have an exercise.
I need to write a function that filters an array and returns people that are 18 or older.

To do that I’m allowed to use only cycles and if statement.

function adultFilter(persons) {
    // return persons.filter(item => item.age >= 18);  - Not valid, i need to use if condition and cycles
   
}

const persons = [
    {name: 'Paul', age: 16},
    {name: 'George', age: 17},
    {name: 'Lucas', age: 21},
    {name: 'Marco', age: 32},
    {name: 'Peter', age: 18},
    {name: 'Carl', age: 13},
    {name: 'Simon', age: 24},
    {name: 'Mark', age: 15},
    {name: 'Sandra', age: 34},
    {name: 'Alice', age: 28}
];

const adults = adultFilter(persons);

console.log(persons);
console.log(adults);

can someone help me and explain how to achieve that. my filter function is not allowed.

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

>Solution :

This should work for you:

function adultFilter(persons) {
  var valid = [];
  for (var i in persons) {
    if (persons[i].age >= 18) {    //eighteen or over, not over eighteen
      valid.push(persons[i]);
    }
  }
  return valid;
}

const persons = [
    {name: 'Paul', age: 16},
    {name: 'George', age: 17},
    {name: 'Lucas', age: 21},
    {name: 'Marco', age: 32},
    {name: 'Peter', age: 18},
    {name: 'Carl', age: 13},
    {name: 'Simon', age: 24},
    {name: 'Mark', age: 15},
    {name: 'Sandra', age: 34},
    {name: 'Alice', age: 28}
];

const adults = adultFilter(persons);

console.log(persons);
console.log(adults);
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