Hi,
I am trying to create a function where I can select a subsection from a array.
I want to select a subsection of an array from a range to call the page from backend.
How do I create a function, to get the page based on the range.
I have currently written a hardcoded solution.
let len = dataArray.length;
let page = 2;
if(len >= 20 && len < 30) {
page = 3;
} else if(len >= 30 && len < 40) {
page = 4;
}else if(len >= 40 && len < 50) {
page = 5;
}else if(len >= 50 && len < 60) {
page = 6;
}else if(len >= 60 && len < 70) {
page = 7;
} else if(len >= 70 && len < 80) {
page = 8;
}else if(len >= 80 && len < 90) {
page = 9;
}else if(len >= 90 && len < 100) {
page = 10;
}else if(len >= 100 && len < 110) {
page = 11;
}else if(len >= 110 && len < 120) {
page = 12;
}else if(len >= 120 && len < 130) {
page = 13;
}else if(len >= 130 && len < 140) {
page = 14;
}else if(len >= 140 && len < 150) {
page = 15;
}
I see a pattern but I am not able to come up with any type of function that will work for this. Can you guide me on how I can get the solution.
Do you mean something like this:
const getPageFromLength = function(length) { if (length % 10 === 0) { return length / 10 + 1; } return Math.ceil(length / 10); }; let len = dataArray.length; let page = getPageFromLength(len); // page is 15 for len == 140Let me explain, what this function does!
length % 10 === 0divides the length by 10 and then checks if the remainder of the operation is 0.? length / 10 + 1if the remainder is 0, the function returns the length divided by 10, plus one. For example, if the length is 140, the remainder is 0. 140 / 10 + 1 equals 15, which is what your conditions above also return.: Math.ceil(length / 10)if the remainder is not equal to zero (for example for 42), the function returns the length divided by 10 and then rounds the result up. So, for 42, that would be 42 / 10 = 4.2, which is 5 rounded up. Also what your logic would return.Edit: Here's an even shorter version:
const getPageFromLength = length => Math.floor(length / 10) + 1;