Home > Blockchain >  function that filter an array using if condition and cycles
function that filter an array using if condition and cycles

Time:03-01

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.

CodePudding user response:

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