Filter Array and return a new array with objects that have been filtered

0

Using Javascript , I created a function as simple as possible that gets a _Array_ of objects Pessoa (example: {name: "Alex", age: 24} ) that returns a new _Array_ only with Pessoa objects that have age between 20 and 30 years.

function Pessoa(nome, idade) {
    this.nome = nome;
    this.idade = idade;
}

var alex = new Pessoa("Alex", 20);

if (idade >= 20 && idade <= 30) {

}

I think it's a little wrong, could anyone help me?

    
asked by anonymous 21.02.2017 / 22:19

1 answer

1

At first you can use the filter function to perform the task, for example;

const inventors = [
  { first: 'Albert', last: 'Einstein', year: 1879, passed: 1955 },
  { first: 'Isaac', last: 'Newton', year: 1643, passed: 1727 },
  { first: 'Galileo', last: 'Galilei', year: 1564, passed: 1642 },
  { first: 'Marie', last: 'Curie', year: 1867, passed: 1934 },
  { first: 'Johannes', last: 'Kepler', year: 1571, passed: 1630 },
  { first: 'Nicolaus', last: 'Copernicus', year: 1473, passed: 1543 },
  { first: 'Max', last: 'Planck', year: 1858, passed: 1947 },
];

var olders = inventor.filter(function(inventor){
    return inventor.year >= 1500;
});

console.log(older);

The variable olders will have an array with the objects where the condition was supplied (year > = 1500)

In your role you could do basically.

function pessoa(objec) {
    var olders = objec.filter(function(person){
        return person.age >= 20 && <= 30;
    });
    return olders;
}
    
21.02.2017 / 22:32