Angel Politis Angel Politis - 3 months ago 6
Javascript Question

Can two loops be merged into one?

I'm using the following function to add specific numbers into an array that I later want to be assigned to a variable. For this I'm using two

for
loops, but I feel like there is a more succinct way to do it. I tried merging the two loops in one without getting an error, but the output is not the same.

Working Example:

function fill () {
var array = [];
for (var index = 0; index < arguments.length; index++) {
for (var number = arguments[index][0]; number <= arguments[index][1]; number++)
array.push(number);
}
return array;
};

/* Use */
var keys = fill([1, 10], [32, 34]);

/* Output */
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 32, 33, 34]





Merged Example:

function fill () {
var array = [];
for (var index = 0, number = arguments[index][0];
index < arguments.length && number <= arguments[index][1];
index++ && number++) {
array.push(number);
}
return array;
};

/* Use */
var keys = fill([1, 10], [32, 34]);

/* Output */
[1, 1]


Is it possible to actually merge the two loops into one? If not, is there a way to write the foregoing function in less code?

Answer

Your code in the first example is fine. There is no real "clean" way to remove the nested loops.

You could iterate over them with forEach, but then you'd still have nested loops, even if one of them is disguised as a function call:

function fill () {
    var array = [];
    Array.prototype.slice.apply(arguments) // Make an array out of arguments.
        .forEach(function(arg){
            for (var number = arg[0]; number <= arg[1]; number++){
                array.push(number);
            }
        });
    return array;
};

console.log(fill([1, 10], [32, 34]));

And you'd have to use Array.prototype.slice.apply to convert arguments to an actual array. (which is ugly)

So, basically, nested loops aren't necessarily "evil". Your first example is as good as it gets.