Skip to content

Instantly share code, notes, and snippets.

@kplawver
Created October 11, 2011 13:23
Show Gist options
  • Save kplawver/1278059 to your computer and use it in GitHub Desktop.
Save kplawver/1278059 to your computer and use it in GitHub Desktop.
I needed to page through results in an array and couldn't find any simple pagination functions through the googles, so I wrote this. I hope it's useful!
function paginateArray(arr,page_num,per_page) {
var i,r=[];
if (arr.length < 1) {
return r;
}
if (per_page == undefined || per_page == null) {
per_page = 10;
}
if (page_num == undefined || page_num == null) {
page_num = 1
} else if (page_num < 1) {
page_num = 1
} else if (page_num == 1) {
start_i = 0;
end_i = per_page;
} else if (page_num == 2) {
start_i = per_page;
end_i = per_page+start_i;
} else if (page_num > 2) {
start_i = ((page_num-1)*per_page)-1;
end_i = start_i+per_page;
}
for (i=start_i;i<end_i;i++) {
if (arr[i] == undefined || arr[i] == null) {
break;
} else {
r.push(arr[i])
}
}
return r;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment