Markus Hallcyon
Markus Hallcyon

Reputation: 371

How do I call all objects from the same constructor function at once?

I'm new to javascript. I want to filter all Employee objects at once and return the names of the ones with equal or over 300 salary. Then I want to store those results into an array. I don't know how to call the method filterSalaries() on all the objects. Please help me.

var EmployeeBlueprint = {

    all_info: function () {
        console.log("Employee: " + this.name + " has a salary of $" + this.salary + ".");
    },
    isMale: function() { return this.gender == "Male"; },
    isFemale: function() { return this.gender == "Female"; },

    filterSalaries: function() {
        if (this.salary >= 300) {
            return this.name;
        }
    }
};

function Employee (name, salary, gender) {
    this.name = name;
    this.salary = salary;
    this.gender = gender;
};

Employee.prototype = EmployeeBlueprint;

var Matt = new Employee("Matt", 100, "Male");
var Alex = new Employee("Alex", 200, "Male");
var Zack = new Employee("Zack", 300, "Male");
var Mark = new Employee("Mark", 400, "Male");
var Rick = new Employee("Rick", 500, "Male");

Upvotes: 1

Views: 76

Answers (1)

six fingered man
six fingered man

Reputation: 2500

Get rid of those variables and store them in an array to begin with.

var emps = [
   new Employee("Matt", 100, "Male"),
   new Employee("Alex", 200, "Male"),
   new Employee("Zack", 300, "Male"),
   new Employee("Mark", 400, "Male"),
   new Employee("Rick", 500, "Male")
];

Then .filter() the Array to get your reduced set and .map() that set to the names.

var low_salary_names = emps.filter(function(emp) {
    return emp.salary <= 300;
}).map(function(emp) {
    return emp.name;
});

Upvotes: 1

Related Questions