I am trying to implement "Next" and "Previous" button to help me navigate through items in an array.
I am using the index of items in the array to get the next or the previous item.
Example:
arrA = [{_id:1,name:"T-Rex"},{_id:3,name:"Predator X"},{_id:4 ,name:"Velociraptor"},{_id: 6, name:"Triceratops"}]
The the id of the current object is represent by
var selectedID = _id
Next and Previous functions
next(){
var idx = arrA.map(x => x._id).indexOf(selectedID);
if (idx === arrA.length - 1){
//return first item
var next_name = arrA[0].name;
} else {
var next_name = arrA[idx + 1].name
}
previous(){
var idx = arrA.map(x => x._id).indexOf(selectedID);
if (idx === arrA[0]){
// return last item
var prev_name = arrA[arrA.length -1].name;
} else{
var prev_name = arrA[idx -1].name
}
}
The expected outcome is that when I click either of the buttons, it should take me to the immediate next or previous item, but the actual outcome is that it loops through the array non-stop.