Find next array index not from start AND if not found loop from beginning

const arr = [{item:'a', value:false}, {item:'b', value:true}, {item:'c', value:true}, {item:'d', value:false}];
const startIndex = 2;

Given startIndex find next object in array with value=true.
Iteration must be forward and, if not found, start from index 0.
Should return arr[1];

I’ve just hit the wall and seems can’t find an iteration method:/

let result = {};
for (let i = startIndex + 1; i < arr.length; i++) {
    if (!arr[i] && i < arr.length) {
        result = arr[i];
    }
}
console.log(result);

3 thoughts on “Find next array index not from start AND if not found loop from beginning”

  1. You could take a single loop and take startIndex as offset and shape the index by the remainder with the length.

    const
        array = [{ item: 'a', value: false }, { item: 'b', value: true }, { item: 'c', value: true }, { item: 'd', value: false }],
        startIndex = 3;
        
    let result;
    
    for (let i = startIndex; i < array.length + startIndex; i++) {
        console.log(i, i % array.length);
        if (array[i % array.length].value) {
            result = array[i % array.length];
            break;
        }
    }
    
    console.log(result);
    Reply
  2. I’m not sure if I understood. But…

    getNext = function(startIndex, arr){
        var i;
        for(i = startIndex; i < arr.length; i++){
            if(arr[i].value){
                return arr[i];
            }
        }
    
        if(startIndex != 0){
            return getNext(0, arr);
        }
        return null;
    }
    
    Reply
  3. You can use .splice to create the two halves:

    • First, search for the element with value=true in the second half, if found, keep in mind to add the length of the first to the index
    • If not found in the second part, search in the first one
    const getElementAtIndexFromStart = (arr=[], startIndex=0) => {
      // get index of element if exists starting from startIndex
      let index = arr.slice(startIndex+1).findIndex(({value}) => value===true);
      if(index!==-1) {
        // if found, add the start index to it to represent the position in in arr
        index = index + startIndex + 1;
      } else {
        // if not found in the second half, search in the first one
        index = arr.slice(0, startIndex+1).findIndex(({value}) => value===true);
      }
      return arr[index];
    }
    
    const arr = [{item:'a', value:false}, {item:'b', value:true}, {item:'c', value:true}, {item:'d', value:false}];
    
    console.log('Start: 0 => ', getElementAtIndexFromStart(arr, 0));
    console.log('Start: 1 => ', getElementAtIndexFromStart(arr, 1));
    console.log('Start: 2 => ', getElementAtIndexFromStart(arr, 2));
    console.log('Start: 3 => ', getElementAtIndexFromStart(arr, 3));
    console.log('Start: 5 => ', getElementAtIndexFromStart(arr, 5));
    Reply

Leave a Comment