Show age between 20 and 30 in an array - Avascript

Asked

Viewed 664 times

0

I would like to create a function as simple as possible that receives an Array of Person objects (example format: {name: "Alex",age: 24} ) that a new one returns array only with objects Person who are aged between 20 and 30 years.

My code is this:

var pessoa = [{
        nome: 'Diego',
        age: 17,
    },
    {
        nome: 'Natalia',
        age: 12,
    },
    {
        nome: 'David',
        age: 27,
    },
    {
        nome: 'Daniel',
        age: 30,
    },
];

function idade(pessoa) {
    if (age => 20 && <= 30) {
        (a partir daqui nao sei como fazer)
    }    
}

I don’t know if the code is right.

1 answer

2

One way is to use the Array#filter javascript to filter only people who enter the age criterion:

var pessoas = [{
    nome: 'Diego',
    age: 17,
  },
  {
    nome: 'Natalia',
    age: 12,
  },
  {
    nome: 'David',
    age: 27,
  },
  {
    nome: 'Daniel',
    age: 30,
  },
];

function idade(pessoas) {
  return pessoas.filter(pessoa => pessoa.age > 19 && pessoa.age < 31);
}

var novoArray = idade(pessoas);
console.log(novoArray);

Using the for classic:

var pessoas = [{
    nome: 'Diego',
    age: 17,
  },
  {
    nome: 'Natalia',
    age: 12,
  },
  {
    nome: 'David',
    age: 27,
  },
  {
    nome: 'Daniel',
    age: 30,
  },
];

function idade(pessoas) {
  let novoArray = [];
  for (let i = 0 ; i < pessoas.length ; i++){
      if (pessoas[i].age > 19 && pessoas[i].age < 31)
         novoArray.push(pessoas[i]);
  }
  return novoArray;
}

var novoArray = idade(pessoas);
console.log(novoArray);

  • 1

    Just a detail that you are using the arrow function ("Arrow Function") that is only available starting with ES6. If you can’t use it, go back to function() { return ...; } inside the callback passed to filter.

  • That’s right, well commented @nbkhope =]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.