let turnorder;
if (Campaign().get('turnorder') === '') turnorder = []; else turnorder = JSON.parse(Campaign.get('turnorder')); const token = ...; // determine token to use for turnorder as appropriate const initiative = ...; // determine initiative as appropriate const turn = { id: token.id, pr: initiative, custom: '', }; if (!turnorder.length) { // if there are no turns, just add the new one turnorder.push(turn); } else { // this code assumes the turnorder was sorted and the 'next turn' has been pressed zero or more times let firstIdx = 0; if (parseInt(turnorder[0].pr) <= parseInt(turnorder[turnorder.length - 1].pr)) { // if the first item in the turnorder should come after the last item, then 'next turn' has been pressed firstIdx = _.findLastIndex(turnorder, (elem, idx, list) => { const curr = parseInt(list[idx].pr); const prev = parseInt(list[idx - 1].pr); return curr > prev; }); } // tail is all of the turn items at the end that should be at the beginning after sorting const tail = turnorder.splice(firstIdx); // move the tail to the front (essentially, sort the turnorder) Array.prototype.unshift.apply(turnorder, tail); // find the position the new item should be inserted at const insert = _.sortedIndex(turnorder, turn, (elem) => parseInt(elem.pr)); turnorder.splice(insert, 0, turn); const head = insert < tail.length ? tail.length + 1 : tail.length; // move items from the front to the back so the same token is first as before Array.prototype.push.apply(turnorder, turnorder.splice(0, head)); } Campaign().set({turnorder: JSON.stringify(turnorder)}); Code is untested, and assumes the turnorder is sorted (from highest to lowest) with the exception of hitting the next turn button (so, something like [4, 3, 2, 1] or [2, 1, 4, 3], but not [1, 3, 4, 2]). If your turnorder is low to high, switch line 19 from <= to >= and switch line 24 from > to <.