Skip to content

Instantly share code, notes, and snippets.

@asduser
Last active October 11, 2016 21:24
Show Gist options
  • Save asduser/3614ac315553fc6cdaa8808371ffbe42 to your computer and use it in GitHub Desktop.
Save asduser/3614ac315553fc6cdaa8808371ffbe42 to your computer and use it in GitHub Desktop.
A special feature to find next\prev item in array only when item has value. Will be skipped all unnecessary items by their id's.
// Go to the next item.
function nextIndex(index, arr){
var item = null;
var minI = 0;
var i = index;
while (i < arr.length) {
i++;
if (i == arr.length) { i = minI; }
if (arr[i].id && arr[i].val) { item = arr[i]; break;}
}
return item;
}
// Go to the previous item.
function prevIndex(index, arr){
var item = null;
var maxI = arr.length;
var i = index;
while (i > 0) {
i--;
if (arr[i].id && arr[i].val) { item = arr[i]; break;}
if (i == 0) { i = maxI; }
}
return item;
}
// Tests.
const arr = [{id:0, val: null}, {id:1, val: null}, {id:2, val: 32}, {id:3, val: null}, {id:4, val: 53}];
nextIndex(2, arr); // {id:4, val: 53}
nextIndex(4, arr); // {id:2, val: 32}
prevIndex(4, arr); // {id:2, val: 32}
// http://plnkr.co/edit/fYpXo1mFRWPxrLlgr123?p=preview
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment