CharliePrynn
CharliePrynn

Reputation: 3080

Javascript split array equally

I have the following json:

http://pastebin.com/uxpWk2CY

And I need to split it into a number of arrays depending on the width of the browser.

Here is my javascript:

    var imageArray = jQuery.parseJSON(data);

    var splitArrayInto = jQuery(document).width() / 300;
    splitArrayInto = Math.floor(splitArrayInto);

    var seperateImageArrays = array_fill(0, splitArrayInto);

    for(var i = 0; i < splitArrayInto; i++){
        seperateImageArrays[i % splitArrayInto][i] = imageArray[i];
    }

When I run that, I get

can't convert undefined to object

seperateImageArrays[i % splitArrayInto][i] = imageArray[i];

Any help is appreciated.

EDIT: Forgot to add the array_fill function.

//PHP array_fill
function array_fill (start_index, num, mixed_val) {
    var key, tmp_arr = {};

    if (!isNaN(start_index) && !isNaN(num)) {
        for (key = 0; key < num; key++) {
            tmp_arr[(key + start_index)] = mixed_val;
        }
    }

    return tmp_arr;
}

Upvotes: 1

Views: 616

Answers (2)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324840

Since you're using array_fill from PHPJS, have you considered using array_chunk? This will separate your big array into equally-sized smaller ones (except the last one, which may have less if the number doesn't divide evenly).

Upvotes: 0

Ja͢ck
Ja͢ck

Reputation: 173662

When you call array_fill you're not passing the third parameter, so all your array elements are set to undefined ... and undefined can't be dereferenced with [i].

Consider passing [] as the third parameter instead.

Upvotes: 3

Related Questions