I have a number of arrays that I need to pull values from depending on the page that is being requested. Each page needs to be assigned a unique combination of data, so for example:
let numbers = ['One', 'Two']
let fruits = ['Apples', 'Oranges']
let colours = ['Red', 'Green']
let names = ['John', 'Jane']
None of the arrays would ever be empty, and so the number of available pages would be the length of all arrays multiplied by each other (so in this case, totalPages would be 16
let totalPages = numbers.length * fruits.length * colours.length * names.length
For every page requested, I need to return a unique set of indices so that every page shows a different group of values, and never more than one from each group.
I currently have nested for-loops (example below) but I was wondering if there's a neater way using the mod operator or something, so that I don't need to rely on the for-loops because at some point I may need to introduce extra arrays and I hate how the nested loops look...
let page = 4 // The requested page (not zero-based index)
let nPage = 1
for(let numberIndex = 0; numberIndex < numbers.length; numberIndex ++) {
for(let fruitIndex = 0; fruitIndex < fruits.length; fruitIndex ++) {
for(let colourIndex = 0; colourIndex < colours.length; colourIndex ++) {
for(let nameIndex = 0; nameIndex < names.length; nameIndex ++) {
// If the loop iteration matches the requested page,
// return the combination of indexes as array
if(page === nPage) {
return [numberIndex, fruitIndex, colourIndex, nameIndex]
}
nPage ++
}
}
}
}
Thanks in advance for any ideas/suggestions :o)