Reputation: 555
so the problem is simple . here i want to return the new nth element of an array according to the previous nth element sent by the user.for example
['1','3','5','7','9','11']
if a user sends a value of 3 then I would like to return 7, if the user sends 5 then I would like to return 9 , if they send 7 then 11 and when they send 11 then I want to return 3. basically its like puting the array in a circular mode and return the next element.
here is my code.
var indices=['1','3','5','7','9','11'];
var index_to_add=2;
var uservalue='1';/// will be sent by the user
var index=indices.indexOf(uservalue);
return indices[index+index_to_add];
everything here works fine but when the array finishes or nears the end then I get undefined instead of element from the first. how can i get the element from the beginning if the element index is undefined or the array finishes?
Upvotes: 0
Views: 59
Reputation: 1057
If I've interpreted your question correctly, a solution would be to encapsulate the processing within a recursive function, if you're after readable code and are unfamiliar with the Modulo function (doing it this way also makes it easier to change the process in the future):
const indices=['1','3','5','7','9','11'];
var index_to_add=2;
var uservalue='1';/// will be sent by the user
console.log(GetElemAtIndex(GetIndex(userValue) + index_to_add));
function GetIndex(userValue) {
return indices.indexOf(userValue); // If this is -1 the user has entered something not in the array
}
function GetElemAtIndex(toFind) {
if (indices.length > toFind) {
return indices[toFind];
}
else {
return GetElemAtIndex(toFind - indices.toLength);
}
}
The modulo function in Taxel's answer is a more efficient way of doing the GetElemAtIndex
block.
Upvotes: 1
Reputation: 4207
Using the Modulo operator:
return indices[(index+index_to_add) % indices.length];
Note: this will only handle the case when uservalue
is actually part of the array. You might want to add a clause like if(index === -1) return 'Uservalue not in array.'
or throw an error.
Upvotes: 3