JSFiddle - React, Tailwind, and code Playground
by core972
HTML
<div id="result"></div>
<button id="previous-button">Previous</button>
<button id="next-button">Next</button>
CSS
#result {
margin: 25px;
min-height: 80px;
border: 1px solid #cdcdcd;
border-radius: 0.25rem;
}
JavaScript
const arrA = [{
_id: 1,
name: "T-Rex"
}, {
_id: 3,
name: "Predator X"
}, {
_id: 4,
name: "Velociraptor"
}, {
_id: 6,
name: "Triceratops"
}];
var selectedID = 1;
function 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
}
}
function 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
}
}
document.getElementById('next-button').click(function(){
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
}
})