2

I need to write a method that, when given a number, constructs an array the length of that number. For instance:

var myArray = constructArray(6);

Now, this is the important part. The array it constructs needs to pair numbers. For instance, if I gave the number 6, the result it returns would look like this:

[2, 2, 1, 1, 0, 0]

And If I gave 5:

[2, 1, 1, 0, 0]

If I gave 4:

[1, 1, 0, 0]

Yeah, you get the point! The numbers are backwards and in pairs (when the length provided is even).

I'm creating a book in CSS and the stacking order (z-index) of the elements needs to follow this pattern, so that pages on top in the DOM are actually on top aesthetically.

2 Answers 2

10
function constructArray(length){
    var result = [];
    for (var i = 0; i < length; i++){
        result.unshift(Math.floor(i / 2));
    }    
    return result;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect. Thank you. This is the code I used to apply your logic to the actual z-index. I just needed help with the logic: pages.css('z-index', function () { return Math.floor(pages.length / 2) - Math.ceil($(this).index() / 2); });
0
function constructArray (a) {
    var arr = new Array();
    var num = 0;
    for (var i=0;i<a;i++) {
        arr.push(num);
        if ((i-1)%2 == 0)
            num++;
    }
    return arr.reverse();
}

Should work :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.