Pagination next and previous for embed discord js - javascript

I have an array that I need to divide into pages with each page showing 4 numbers. I need help on the Next and Previous page commands.
There's an answer about this before in here: How to separate my array into some parts in discord.js?, but I couldn't make it work. Using splice modifies the original array and rearranges the index so the formula there of currentPage * pageSize - pageSize for the next page start index isn't working properly.
Here are the variables for my pagination
let numberArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
let currentPage = 1;
let pageSize = 4;
const countPages = Math.ceil(input.length / pageSize);
Here's the code to show the initial page which shows 1, 2, 3, 4
numberArray.splice(0, pageSize);
Here's the code for Next but this outputs 9, 10, 11, 12.
const nextPage = currentPage + 1;
if (nextPage <= countPages) {
currentPage = nextPage;
const startIndex = currentPage * pageSize - pageSize;
numberArray.splice(startIndex, pageSize)
}

You shouldn't use splice as it modifies the original array. Although you already know this, you can run the following snippet and see how splice removed those four items from the original array:
let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let pageContent = array.splice(4, 4)
console.log('pageContent:', pageContent.toString())
console.log('array:', array.toString())
You could use slice instead that returns a new array:
let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let pageContent = array.slice(4, 8)
console.log('pageContent:', pageContent.toString())
console.log('array:', array.toString())
You could also create a class for this:
class Paginator {
constructor(array, pageSize) {
this.array = array;
this.pageSize = pageSize;
this.currentPage = 1;
}
getPage() {
const startIndex = (this.currentPage - 1) * this.pageSize;
return this.array.slice(startIndex, startIndex + this.pageSize);
}
next() {
if (this.currentPage * this.pageSize < this.array.length) {
this.currentPage += 1;
}
return this.getPage();
}
previous() {
if (this.currentPage > 1) {
this.currentPage -= 1;
}
return this.getPage();
}
first() {
this.currentPage = 1;
return this.getPage();
}
last() {
this.currentPage = Math.ceil(this.array.length / this.pageSize);
return this.getPage();
}
}
let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let pageSize = 4
let paginator = new Paginator(array, pageSize)
console.log(`
First: ${paginator.first()}
Next: ${paginator.next()}
Next: ${paginator.next()}
Previous: ${paginator.previous()}
Last: ${paginator.last()}
`)

Related

How to get next and previous five element of from an array?

I have an array which consist n element.
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
and also have two button next and prev and initially i am showing the first 5 element(on page load) of an array initial array [1, 2, 3, 4, 5]
how i can show the next five elements on the next button click [6, 7, 8, 9, 10] and on previous button click want to show the [1, 2, 3, 4, 5]
and also need to check the if it does not have any next element if lastIndex is included and if array includes first element.
i have tried using slice to arr.slice(begin[, end])
const arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
const size = 5
let current = 1
function prev(){
if(current > 1){
current--
let newArr = getNewArr()
console.log(newArr)
}
}
function next(){
if(current >= 1 && current < arr.length/size){
current++
let newArr = getNewArr()
console.log(newArr)
}
}
function getNewArr(){
return arr.slice(size*current - size, size*current)
}
<button onclick=prev()>prev</button>
<button onclick=next()>next</button>
You could take an index and a size for the wanted elements ans dlice the array.
const
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],
show = array => document.getElementById('items').innerHTML = array.join(' '),
next = () => {
index += size;
while (index >= data.length) index -= size;
show(data.slice(index, index + size));
},
prev = () => {
index -= size;
while (index < 0) index += size;
show(data.slice(index, index + size));
},
size = 5;
let index = 0;
document.getElementById('bprev').addEventListener('click', prev);
document.getElementById('bnext').addEventListener('click', next);
show(data.slice(index, index + size));
<button id="bprev">prev</button> <span id="items"></span> <button id="bnext">next</button>
For now I am just creating a demo with the hardcoded pageNumber in next and previous click events but you can make it dynamic based on the array size.
Working Demo :
// Input array
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Method which returns the updated array elements based on the pageSize and pageNumber.
const paginate = (array, pageSize, pageNumber) => {
return array.slice((pageNumber - 1) * pageSize, pageNumber * pageSize);
}
// On load initializing 5 elements.
document.getElementById('content').innerHTML = paginate(arr, 5, 1);
// Next button click event
document.getElementById('next').onclick = function() {
document.getElementById('content').innerHTML = paginate(arr, 5, 2);
};
// previous button click event
document.getElementById('previous').onclick = function() {
document.getElementById('content').innerHTML = paginate(arr, 5, 1);
};
<button id="previous">Previous</button>
<span id="content"></span>
<button id="next">Next</button>

How to randomize 2 lists so that items of the same index aren't identical?

Say I have 2 lists with identical items that I've shuffled like below:
listA = [1, 3, 2];
listB = [2, 3, 1];
I want to make sure that list items of the same index don't match. So I wouldn't want listA[1] to match with listB[1]. How do I randomize both lists so that this doesn't occur?
There is probably a more elegant way to do this, but the code below should work, even for arrays of different sizes. It first checks whether it's possible to get the uniqueness you're looking for, and if so it goes into a while loop to continuously shuffle the larger of the two arrays (in place) until it finds a solution.
// First, set up utility functions
function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
}
function smallerAndOther(arr1, arr2) {
const smallerArr = arr1.length < arr2.length ? arr1 : arr2;
const otherArr = smallerArr === arr1 ? arr2 : arr1;
return [smallerArr, otherArr];
}
function anyEqualIdx(arr1, arr2) {
const [smallerArr, otherArr] = smallerAndOther(arr1, arr2);
for (let i of smallerArr.keys()) {
if (smallerArr[i] === otherArr[i]) return true;
}
return false;
}
function getCount(array, value) {
return array.filter((v) => (v === value)).length;
}
// Now for the real stuff
function sufficientUnique(arr1, arr2) {
const [smallerArr, otherArr] = smallerAndOther(arr1, arr2);
for (let num of new Set([...smallerArr])) {
if (otherArr.length - getCount(otherArr, num) < getCount(smallerArr, num)) {
return false;
}
}
return true;
}
function shuffleUniqueIdxs(arr1, arr2) {
if (!sufficientUnique(arr1, arr2)) {
console.log("Error: Not enough unique values to meet constraint.");
return;
}
const largerArr = arr1.length > arr2.length ? arr1 : arr2;
while (anyEqualIdx(arr1, arr2)) {
shuffleArray(largerArr);
}
console.log("Success: ", arr1, arr2);
}
// Testing
let listA = [1, 3, 2];
let listB = [2, 3, 1];
shuffleUniqueIdxs(listA, listB);
listA = [7, 5, 5, 3, 9, 9, 1];
listB = [3, 5, 5];
shuffleUniqueIdxs(listA, listB);
listA = [1, 1, 1];
listB = [2, 1, 1];
shuffleUniqueIdxs(listA, listB); // shows error message
listA = [1, 1, 1, 1, 1];
listB = [2, 2, 2, 2, 2];
shuffleUniqueIdxs(listA, listB);
listB = [99, 9, 9, 9, 9, 9, 9, 9, 99, 88, 8, 8, 8, 8, 8, 7, 7, 6, 65, 5, 5, 5, 4]
listA = [9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 6];
shuffleUniqueIdxs(listA, listB);
Here's one solution. It first individually shuffles both arrays, then it looks for repeated entries and randomly moves those around. Note that this solution only works for arrays of the same size. It is also intended to be used on arrays where most elements are unique (otherwise, it might get stuck randomly moving things around for a while).
const randIntBetween = (left, right) => left + Math.floor(Math.random() * (right - left));
function shuffle(array) {
array = [...array];
for (let i = 0; i < array.length; ++i) {
const newIndex = randIntBetween(i, array.length);
[array[i], array[newIndex]] = [array[newIndex], array[i]];
}
return array;
}
function randomlyMoveRepeatedEntries(array, comparisonArray) {
array = [...array];
const indicesToCheck = new Set(array.map((_, i) => i));
while (indicesToCheck.size) {
const { value: index } = indicesToCheck.values().next();
if (array[index] !== comparisonArray[index]) {
indicesToCheck.delete(index);
continue;
}
const newIndex = randIntBetween(index, array.length);
[array[index], array[newIndex]] = [array[newIndex], array[index]];
indicesToCheck.add(newIndex);
}
return array;
}
// ----- Example Usage ----- //
const listA = shuffle([1, 2, 3, 4, 5]);
const listB = randomlyMoveRepeatedEntries(shuffle([1, 2, 3, 4, 5]), listA);
console.log(listA.join(', '));
console.log(listB.join(', '));

Array of numbers to batches of given sum

I've a JavaScript array and sum as input
array = [4,8,2,4,2,2,8,12,4,2, 2]
sum = 12 // all the time sum will be 12
I want 2d array, the numbers in batches should be sum equals or less than 12
The output array should look like
[
[4,8],
[2,4,2,2,2],
[8, 4],
[12],
[2]
]
4 + 8 = 12
2 + 4 + 2 + 2 + 2 = 12
...
2 is left at the end
Other examples
1) array = [6,5,3,3,3,2,2,2,2]
sum = 12
output: [ [6,3,3], [5,3,2,2], [2,2] ]
One the number is allotted to subset, it should not used to other subset
remaining numbers can be added to the last but sum should be less than 12, else add one more array and add remaining ones
The input array can have any integer from 1 - 12
How can I get the output I want?
Try this function. I commented the code as much as possible to clarify it.
const example1 = [4, 8, 2, 4, 2, 2, 8, 12, 4, 2, 2];
const example2 = [6, 5, 3, 3, 3, 2, 2, 2, 2];
const example3 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
const example4 = [5,12,3,4,4,1,1,1,5,8,12,6,9,11,6];
const example5 = [4, 2, 1, 2, 3, 3, 5, 7, 8, 9];
const lookAhead = function(array, searchFor) {
return array.some(val => {
return val <= searchFor;
});
}
function findPairs(inputArray) {
// First sort array in descending order
inputArray.sort((a, b) => b - a);
console.log("input", JSON.stringify(inputArray.slice(0)));
// set variables
const pairArray = [];
const max = 12;
inputArray.forEach(function(num, index) {
// when looping the array we will replace values with null once completed,
// Therefore if value is null no need to go futher
if (num == null)
return;
// initiate pair value with current number
const pair = [num];
// set it to null in input array
inputArray[index] = null;
// if number equals to max (ie. 12) no need to go futher
if (num == max) {
pairArray.push(pair);
return;
}
let total = num;
// Loop through array again to see matching numbers
for (let i = 0; i < inputArray.length; i++) {
// Don't go futher if it is a null value
if (inputArray[i] == null)
continue;
const add = total + inputArray[i];
/* if the total is less than max (12) then we check if we have an edge case
* For example in an array like [6, 5, 3, 3, 3], 6 + 5 is 11 but in next loops we
* will not find any "1" to get to 12. Therefore we escape this iteration and check
* next numbers. In this case the result would be 6 + 3 + 3
*/
if (add < max) {
const found = lookAhead(inputArray.slice(i), max - add);
if (found) {
pair.push(inputArray[i]);
total = add;
inputArray[i] = null;
}
} else if (add == max) {
// The addition is equals to max. Push the number and set it to null in input array
pair.push(inputArray[i]);
inputArray[i] = null;
total = 0;
break;
}
}
// Push pair array from this iteration to pairArray
pairArray.push(pair);
});
console.log("output", JSON.stringify(pairArray));
console.log("-------");
}
findPairs(example1);
findPairs(example2);
findPairs(example3);
findPairs(example4);
findPairs(example5);
A little complex to understand but here you go...
let originalArray = [7, 7, 7, 7, 7]
let sum = 12;
let twoDiArray = [];
let CalculateSum = (array, element) => {
array = [...array, element]
return array.reduce((x, y) => {
return x + y;
})
}
twoDiArray.push([]);
originalArray.forEach(element => {
for (let i = 0; i < twoDiArray.length; i++) {
if (CalculateSum(twoDiArray[i], element) <= 12) {
twoDiArray[i].push(element);
break;
} else {
if (twoDiArray.length - 1 === i) {
twoDiArray.push([element]);
break;
}
}
}
})
console.log(twoDiArray)
Here you... I will keep both answers open for future use of others...
let originalArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
let sum = 12;
let twoDiArray = [];
let CalculateSum = (array, element) => {
array = [...array, element]
return array.reduce((x, y) => {
return x + y;
})
}
twoDiArray.push([originalArray[0]]);
originalArray.splice(0, 1);
do {
originalArray.forEach((element, index) => {
for (let i = 0; i < twoDiArray.length; i++) {
let summ = CalculateSum(twoDiArray[i], element);
if (summ === 12) {
twoDiArray[i].push(element);
originalArray.splice(index, 1);
break;
} else {
if (index === originalArray.length - 1) {
if (CalculateSum(twoDiArray[twoDiArray.length - 1], originalArray[0]) <= 12) {
twoDiArray[twoDiArray.length - 1].push(originalArray[0]);
break;
} else {
twoDiArray.push([originalArray[0]]);
}
originalArray.splice(0, 1);
}
}
}
})
}
while (originalArray.length > 0);
console.log(twoDiArray)

Slice() doesn't display if array contains less then end number [duplicate]

I am trying to write a Javascript function that takes an array, page_size and page_number as parameters and returns an array that mimics paginated results:
paginate: function (array, page_size, page_number) {
return result;
}
so for example when:
array = [1, 2, 3, 4, 5],
page size = 2,
page_number = 2,
the function should return: [3, 4].
Any ideas would be appreciated.
You can use Array.prototype.slice and just supply the params for (start, end).
function paginate(array, page_size, page_number) {
// human-readable page numbers usually start with 1, so we reduce 1 in the first argument
return array.slice((page_number - 1) * page_size, page_number * page_size);
}
console.log(paginate([1, 2, 3, 4, 5, 6], 2, 2));
console.log(paginate([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], 4, 1));
Here's a solution with reduce():
function paginate (arr, size) {
return arr.reduce((acc, val, i) => {
let idx = Math.floor(i / size)
let page = acc[idx] || (acc[idx] = [])
page.push(val)
return acc
}, [])
}
let array = [1, 2, 3, 4, 5]
let page_size = 2
let pages = paginate(array, page_size)
console.log(pages) // all pages
console.log(pages[1]) // second page
It returns an array of pages so you can get a certain page, or loop through all of them.
I saw an example above that did this correctly (kind of) and wanted to expand on it.
This was the example.
function paginate(array, page_size, page_number) {
// human-readable page numbers usually start with 1, so we reduce 1 in the first argument
return array.slice((page_number - 1) * page_size, page_number * page_size);
}
There are a few things wrong with this.
1.) If the page_number is 0 then it will try and set the starting split at -1 * page_size which returns an empty array. So the minimum value of the page_number attr should be 1, never anything less unless you handle that case in the function.
2.) The starting and ending index of the split are the same. Because of this, you get back an empty array. So the split should be:
return array.split(page_number * page_size, page_number * page_size + page_size)
const myArray = [1,2,3,4,5,6,7,8,9,10];
const paginateBad1 = (array, page_size, page_number) => {
return array.slice((page_number - 1) * page_size, page_number * page_size);
};
const paginateBad2 = (array, page_size, page_number) => {
return array.slice(page_number * page_size, page_number * page_size);
};
const paginateGood = (array, page_size, page_number) => {
return array.slice(page_number * page_size, page_number * page_size + page_size);
};
console.log("Bad 1", paginateBad1(myArray, 2, 0));
console.log("Bad 2", paginateBad2(myArray, 2, 1));
console.log("Good", paginateGood(myArray, 2, 1));
Another aproach that you can utilize, is using .filter, look:
const paginate = function (array, index, size) {
// transform values
index = Math.abs(parseInt(index));
index = index > 0 ? index - 1 : index;
size = parseInt(size);
size = size < 1 ? 1 : size;
// filter
return [...(array.filter((value, n) => {
return (n >= (index * size)) && (n < ((index+1) * size))
}))]
}
var array = [
{id: "1"}, {id: "2"}, {id: "3"}, {id: "4"}, {id: "5"}, {id: "6"}, {id: "7"}, {id: "8"}, {id: "9"}, {id: "10"}
]
var transform = paginate(array, 2, 5);
console.log(transform) // [{"id":"6"},{"id":"7"},{"id":"8"},{"id":"9"},{"id":"10"}]
You can use Array.filter() with the help of its second parameter (the index of the current element being processed in the array).
You'll also need the currently selected page and the number of items per page to display, so you can find the minimum and maximum index of the elements needed.
const indexMin = selectedPage * elementsPerPage;
const indexMax = indexMin + elementsPerPage;
const paginatedArray = arrayToPaginate.filter(
(x, index) => index >= indexMin && index < indexMax
);
Updating the selectedPage and/or the elementsPerPage value will allow to return the correct items to display.
The use of Array#slice is the expected answer.
Here I use Symbol.iterator to create an iterable.
const arr = [1,2,3,4,5,6,7,8,9,10]
function page({arr, pageSize, pageNumber}) {
const start = pageSize*(pageNumber-1)
const end = pageSize*pageNumber
return {
*[Symbol.iterator]() {
for(let i = start; i < arr.length && i < end; i++) {
yield arr[i]
}
}
}
}
console.log([...page({arr, pageSize: 5, pageNumber: 2})])
Hey I'm sorry I'm a bit late but we can use the Array.splice(start, end) method except this is much simpler
const page = 2
const step = 2;
const start = page * step - step;
const end = start + step;
const array = [1,2,3,4,5,6]
console.log(array.splice(start, end))
Here is another variation using Array.from with Array.slice
const paginate = (array, n) => {
const pageSize = Math.ceil(array.length / n);
return Array.from({ length: pageSize }, (_, index) => {
const start = index * n;
return array.slice(start, start + n);
});
};
function paginate(array, page_size, page_number) {
// human-readable page numbers usually start with 1, so we reduce 1 in the first argument
return array.slice((page_number - 1) * page_size, page_number * page_size);
}
var arr = [1, 2, 3, 4, 5, 6]
const options = {
//page: parseInt(req.query.page) || 1,
page:1,
limit:10
//limit: parseInt(req.query.limit) || 10,
//customLabels: servCustomLabels,
};
let prev_page = 0;
let next_page = 0;
let h_p_p = null;
let h_n_p = null;
let page_count = Math.ceil((arr.length / options.limit));
if (options.page >= page_count ){ // 2 3
next_page = 0;
}
if(options.page >= 1 && options.page < page_count ){
next_page = options.page + 1;
h_n_p = true;
}else{
next_page = 0;
h_n_p = false;
}
if(options.page <= 1 ){
prev_page =0;
h_p_p = false;
}else{
prev_page = options.page -1 ;
h_p_p = true;
}
console.log(paginate(arr, 2, 2));
console.log({paginator: {
totalDocs: arr.length,
perPage: options.limit,
pageCount: page_count,
currentPage: options.page,
//slNo: 2,
hasPrevPage: h_p_p,
hasNextPage: h_n_p,
prev: prev_page,
next: next_page
}})
function paginate(arr, PerPage) {
let map = {};
let startPage = 1;
arr.forEach((current) => {
if (map[startPage] && map[startPage].length < PerPage) {
map[startPage].push(current);
}
if (!map[startPage]) {
map[startPage] = [current];
}
if (map[startPage] && map[startPage].length >= PerPage) {
startPage++;
}
});
return map;
}
you will find an example on this link
The example below is using iter-ops library (I'm the author).
// our inputs...
const array = [1, 2, 3, 4, 5];
const pageSize = 2;
const pageIndex = 1;
The most efficient way is to process an array as an iterable, so you go through it once.
If you never need other pages, then the fastest way is like this:
import {pipe, skip, page} from 'iter-ops';
const p = pipe(
array,
skip(pageSize * pageIndex), // skip pages we don't want
page(pageSize) // create the next page
).first;
console.log(p); //=> [3, 4]
And if you do need other pages, then you can do:
const p = pipe(
array,
page(pageSize), // get all pages
skip(pageIndex) // skip pages we don't want
).first;
console.log(p); //=> [3, 4]
And in case you need to do further processing:
const i = pipe(
array,
page(pageSize), // get all pages
skip(pageIndex), // skip pages we don't want
take(1), // take just one page
// and so on, you can process it further
);
console.log([...i]); //=> [[3, 4]]
A simple solution using filter:
function paginate(array, pageIndex, pageSize) {
const first = pageIndex * pageSize
const last = (pageIndex * pageSize) + pageSize
return array.filter((_, index) => {
return first <= index && index < last
})
}
for (let pageNum = 1; pageNum <= totalPagesCount; pageNum++){
....
const chunk = articles.slice(
(pageNum - 1) * pageSizeNumbered,
pageNum * pageSizeNumbered,
);
.....
}
I'd go with something like this;
const paginateArray = (array, pageNumber, pageSize) => {
const page = array.slice((pageNumber - 1) * pageSize, pageNumber * pageSize);
return page;
};
const array = [1, 2, 3, 4, 5];
const pageSize = 2;
const pageNumber = 2;
console.log(paginateArray(array, pageNumber, pageSize));

Paginate Javascript array

I am trying to write a Javascript function that takes an array, page_size and page_number as parameters and returns an array that mimics paginated results:
paginate: function (array, page_size, page_number) {
return result;
}
so for example when:
array = [1, 2, 3, 4, 5],
page size = 2,
page_number = 2,
the function should return: [3, 4].
Any ideas would be appreciated.
You can use Array.prototype.slice and just supply the params for (start, end).
function paginate(array, page_size, page_number) {
// human-readable page numbers usually start with 1, so we reduce 1 in the first argument
return array.slice((page_number - 1) * page_size, page_number * page_size);
}
console.log(paginate([1, 2, 3, 4, 5, 6], 2, 2));
console.log(paginate([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], 4, 1));
Here's a solution with reduce():
function paginate (arr, size) {
return arr.reduce((acc, val, i) => {
let idx = Math.floor(i / size)
let page = acc[idx] || (acc[idx] = [])
page.push(val)
return acc
}, [])
}
let array = [1, 2, 3, 4, 5]
let page_size = 2
let pages = paginate(array, page_size)
console.log(pages) // all pages
console.log(pages[1]) // second page
It returns an array of pages so you can get a certain page, or loop through all of them.
I saw an example above that did this correctly (kind of) and wanted to expand on it.
This was the example.
function paginate(array, page_size, page_number) {
// human-readable page numbers usually start with 1, so we reduce 1 in the first argument
return array.slice((page_number - 1) * page_size, page_number * page_size);
}
There are a few things wrong with this.
1.) If the page_number is 0 then it will try and set the starting split at -1 * page_size which returns an empty array. So the minimum value of the page_number attr should be 1, never anything less unless you handle that case in the function.
2.) The starting and ending index of the split are the same. Because of this, you get back an empty array. So the split should be:
return array.split(page_number * page_size, page_number * page_size + page_size)
const myArray = [1,2,3,4,5,6,7,8,9,10];
const paginateBad1 = (array, page_size, page_number) => {
return array.slice((page_number - 1) * page_size, page_number * page_size);
};
const paginateBad2 = (array, page_size, page_number) => {
return array.slice(page_number * page_size, page_number * page_size);
};
const paginateGood = (array, page_size, page_number) => {
return array.slice(page_number * page_size, page_number * page_size + page_size);
};
console.log("Bad 1", paginateBad1(myArray, 2, 0));
console.log("Bad 2", paginateBad2(myArray, 2, 1));
console.log("Good", paginateGood(myArray, 2, 1));
Another aproach that you can utilize, is using .filter, look:
const paginate = function (array, index, size) {
// transform values
index = Math.abs(parseInt(index));
index = index > 0 ? index - 1 : index;
size = parseInt(size);
size = size < 1 ? 1 : size;
// filter
return [...(array.filter((value, n) => {
return (n >= (index * size)) && (n < ((index+1) * size))
}))]
}
var array = [
{id: "1"}, {id: "2"}, {id: "3"}, {id: "4"}, {id: "5"}, {id: "6"}, {id: "7"}, {id: "8"}, {id: "9"}, {id: "10"}
]
var transform = paginate(array, 2, 5);
console.log(transform) // [{"id":"6"},{"id":"7"},{"id":"8"},{"id":"9"},{"id":"10"}]
You can use Array.filter() with the help of its second parameter (the index of the current element being processed in the array).
You'll also need the currently selected page and the number of items per page to display, so you can find the minimum and maximum index of the elements needed.
const indexMin = selectedPage * elementsPerPage;
const indexMax = indexMin + elementsPerPage;
const paginatedArray = arrayToPaginate.filter(
(x, index) => index >= indexMin && index < indexMax
);
Updating the selectedPage and/or the elementsPerPage value will allow to return the correct items to display.
The use of Array#slice is the expected answer.
Here I use Symbol.iterator to create an iterable.
const arr = [1,2,3,4,5,6,7,8,9,10]
function page({arr, pageSize, pageNumber}) {
const start = pageSize*(pageNumber-1)
const end = pageSize*pageNumber
return {
*[Symbol.iterator]() {
for(let i = start; i < arr.length && i < end; i++) {
yield arr[i]
}
}
}
}
console.log([...page({arr, pageSize: 5, pageNumber: 2})])
Hey I'm sorry I'm a bit late but we can use the Array.splice(start, end) method except this is much simpler
const page = 2
const step = 2;
const start = page * step - step;
const end = start + step;
const array = [1,2,3,4,5,6]
console.log(array.splice(start, end))
Here is another variation using Array.from with Array.slice
const paginate = (array, n) => {
const pageSize = Math.ceil(array.length / n);
return Array.from({ length: pageSize }, (_, index) => {
const start = index * n;
return array.slice(start, start + n);
});
};
function paginate(array, page_size, page_number) {
// human-readable page numbers usually start with 1, so we reduce 1 in the first argument
return array.slice((page_number - 1) * page_size, page_number * page_size);
}
var arr = [1, 2, 3, 4, 5, 6]
const options = {
//page: parseInt(req.query.page) || 1,
page:1,
limit:10
//limit: parseInt(req.query.limit) || 10,
//customLabels: servCustomLabels,
};
let prev_page = 0;
let next_page = 0;
let h_p_p = null;
let h_n_p = null;
let page_count = Math.ceil((arr.length / options.limit));
if (options.page >= page_count ){ // 2 3
next_page = 0;
}
if(options.page >= 1 && options.page < page_count ){
next_page = options.page + 1;
h_n_p = true;
}else{
next_page = 0;
h_n_p = false;
}
if(options.page <= 1 ){
prev_page =0;
h_p_p = false;
}else{
prev_page = options.page -1 ;
h_p_p = true;
}
console.log(paginate(arr, 2, 2));
console.log({paginator: {
totalDocs: arr.length,
perPage: options.limit,
pageCount: page_count,
currentPage: options.page,
//slNo: 2,
hasPrevPage: h_p_p,
hasNextPage: h_n_p,
prev: prev_page,
next: next_page
}})
function paginate(arr, PerPage) {
let map = {};
let startPage = 1;
arr.forEach((current) => {
if (map[startPage] && map[startPage].length < PerPage) {
map[startPage].push(current);
}
if (!map[startPage]) {
map[startPage] = [current];
}
if (map[startPage] && map[startPage].length >= PerPage) {
startPage++;
}
});
return map;
}
you will find an example on this link
The example below is using iter-ops library (I'm the author).
// our inputs...
const array = [1, 2, 3, 4, 5];
const pageSize = 2;
const pageIndex = 1;
The most efficient way is to process an array as an iterable, so you go through it once.
If you never need other pages, then the fastest way is like this:
import {pipe, skip, page} from 'iter-ops';
const p = pipe(
array,
skip(pageSize * pageIndex), // skip pages we don't want
page(pageSize) // create the next page
).first;
console.log(p); //=> [3, 4]
And if you do need other pages, then you can do:
const p = pipe(
array,
page(pageSize), // get all pages
skip(pageIndex) // skip pages we don't want
).first;
console.log(p); //=> [3, 4]
And in case you need to do further processing:
const i = pipe(
array,
page(pageSize), // get all pages
skip(pageIndex), // skip pages we don't want
take(1), // take just one page
// and so on, you can process it further
);
console.log([...i]); //=> [[3, 4]]
A simple solution using filter:
function paginate(array, pageIndex, pageSize) {
const first = pageIndex * pageSize
const last = (pageIndex * pageSize) + pageSize
return array.filter((_, index) => {
return first <= index && index < last
})
}
for (let pageNum = 1; pageNum <= totalPagesCount; pageNum++){
....
const chunk = articles.slice(
(pageNum - 1) * pageSizeNumbered,
pageNum * pageSizeNumbered,
);
.....
}
I'd go with something like this;
const paginateArray = (array, pageNumber, pageSize) => {
const page = array.slice((pageNumber - 1) * pageSize, pageNumber * pageSize);
return page;
};
const array = [1, 2, 3, 4, 5];
const pageSize = 2;
const pageNumber = 2;
console.log(paginateArray(array, pageNumber, pageSize));

Categories