return tuple of array indexes based on previous next incrementing in javascript

You can use a for loop to iterate through the array and check if the next element is greater than the current element by 1. If it is, you can push the index of the current element and the index of the next element to a result array. Once the loop is done, you can return the result array as a tuple.

Here's the code that does this:

index.tsx
function getIncrementingIndexes(arr) {
  const result = [];
  for (let i = 0; i < arr.length - 1; i++) {
    if (arr[i + 1] === arr[i] + 1) {
      result.push([i, i + 1]);
    }
  }
  return result;
}

const arr = [1, 2, 3, 6, 7, 8, 10];
const result = getIncrementingIndexes(arr);
console.log(result); // [[0, 1], [1, 2], [4, 5]]
332 chars
14 lines

In this example, the input array [1, 2, 3, 6, 7, 8, 10] has incrementing sequences [1, 2, 3] and [6, 7, 8], so the returned tuple [[0, 1], [1, 2], [4, 5]] contains the indexes of these sequences.

gistlibby LogSnag