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

Asked

Viewed 600 times

0

Using Javascript, created a function as simple as possible that receives a _Array_ object Pessoa (example: {name: "Alex", age: 24}) that a new one returns _Array_ only with objects Pessoa between the ages of 20 and 30.

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, someone could help me?

  • 1

    It’s very wrong. I won’t do it for you. But you already know what it is array? Do you know how to create it? If you don’t know this exercise is too advanced for you. Do you know how to create function, understand the concept? You need to understand how these things work before you do this.

  • You haven’t even created a Person object. And that age within that if, it doesn’t even exist. And if it’s really an array of objects, you’ll need a foeach to iterate on each object of the array items.

1 answer

1

At first you can use the function filter to accomplish 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 tera an array with the objects where the condition was supplied (year >= 1500)

In your job you could do basically.

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

Browser other questions tagged

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