Say I have an array that looks like this
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
These array represents page numbers in my scenario. Say if I am on page 8, I'd like to create a seperate array that includes the following The first 5 before page 8 and the first 5 after page 8.
i.e first 11 items array.
[3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
Therefore having 11 items in an array including that page itself.
If the array is smaller than 5, then simply return the rest.
i.e
if the array looks like this [2,3,4,5,6,7,8]
and if the page is 4, since the before does not have 5 items exactly I'd like to get all of it.
You can use the slice method of the Array.
function paginatorNumbers(arr, currentIndex) {
return arr.length > 5 && currentIndex > 5
? arr.slice(currentIndex - 6, currentIndex + 5)
: arr.slice(0, currentIndex + 5)
}
EDITED:
This should work now
const getRange = (array, index) => {
// You need constraints if index - 5 is < 0
const startIndex = Math.max(0, index - 5 - 1);
const endIndex = index+ 5;
return array.slice(startIndex, endIndex);
}
You can makeit very simple with Plus and Minus.
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
function getRange(current) {
let start = (current -5)
let end = (current + 5)
let res = []
start = start < 0 ? 0 : start
for(start; start <= end; start++) {
res.push(start)
}
return res;
}
console.log(getRange(8)) // starts from 3
console.log(getRange(2)) // starts from 0