NodeJS dynamic replicaset array

Folks, is there a way to make the following block dynamic, based upon the length of the hosts and ports array? Either using underscore.each, or something similar?

var hosts = ['ip1','ip2','ip3];
var ports = ['port1','port2','port3'];
this.replSet = new ReplSetServers([
    new Server(this.hosts[0], this.ports[0]),
    new Server(this.hosts[1], this.ports[1]),
    new Server(this.hosts[2], this.ports[2])
]);

Thanks!

I've tried with no avail:

this.servers = [];
_.each(this.hosts, function (this.host) {
    this.servers.push(new Server(this.hosts[0], this.ports[0]));
});

Thanks!

The syntax is wrong, the first parameter of the _.each callback is the current element and the second one is the index. You can iterate through one of the arrays and use the index for selecting the corresponding element in the second array:

_.each(hosts, function (element, index) {
    this.servers.push(new Server(element, ports[index]));
});

You could also use the _.map method:

this.servers = _.map(hosts, function (element, index) {
    return new Server(element, ports[index]);
});

You have a mistake within the each loop; you are always using hosts[0].

var hosts = ['ip1','ip2','ip3];
var ports = ['port1','port2','port3'];

this.servers = [];
_.each(hosts, function (host,index) {
    this.servers.push(new Server(host, ports[index]));
});
this.replSet = new ReplSetServers(this.servers);

Besides you can use _.map:

var hosts = ['ip1','ip2','ip3];
var ports = ['port1','port2','port3'];
this.servers = _.map(hosts, function (host,index) {
    return new Server(host, ports[index]);
});
this.replSet = new ReplSetServers(this.servers);

This works :

var servers = [];
_.each(hosts, function (host, index) {
    servers.push(new Server(host , ports[index]));
});
this.replSet = new ReplSetServers(servers);

Thanks Guys!