Home > Software engineering >  How can I split the result of an array in an ejs into multiple pages?
How can I split the result of an array in an ejs into multiple pages?

Time:08-10

I'm building a blog using nodejs, express and mongodb. When I go to create an article, it is saved in a database that includes all the articles. On the homepage I used an array with object to store all the articles locally and get the title, content and more from them. I wanted to know how you can set up page navigation so that previews of only 10 articles are shown per page (first page 10 articles; second page 10 articles and so on). So I wanted to know how to set a radius of objects to take from the array (first page 1 to 10; second page 11 to 20 and so on).

CodePudding user response:

Let say you have an array with 100 element and you want to split to get an array of 10 x 10 element (10 pages of 10 element)

let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100];

let pages = [];
while(arr.length > 0) {
    pages.push(
    arr.splice(0, 10)
  );
}

console.log(arr)
console.log(pages)

Now you have an array with 10 sub-array of 10 elements each.

Image you want to print the page number 5 you have yo do something like this :

let page = 5;
let articles = pages[page-1]

for(let article of articles ) {
    // render your article preview here
}

This is just an exemple to give you an idea about how to split an array into multiple pages ;)

  • Related