Rohit Rohit - 8 months ago 50
Javascript Question

check if elements in array are consecutive --- javascript

I have an array as

arr = [1,2,3,4,6,7,8,9]

Now I want to check if the values in the array are consecutive.

Being more specific, I want this

First Check gives first and second element are consecutive and the next element is not consecutive then the algo must return the first element from where the consecutive number started


First Check will give 1
Second Check will give 6
and so on...

Please help
Thanks in advance


One sidenote is that you want to call it multiple times, so each call should know which array it's working on and what the previous offset in that array was. One thing you can do is to extend the native Array object. [Demo]

Array.prototype.nextCons = (function () {
  var offset = 0; // remember the last offset
  return function () {
    var start = offset, len = this.length;
    for (var i = start + 1; i < len; i++) {
      if (this[i] !== this[i-1] + 1) {
    offset = i;
    return this[start];


var arr =  [1,2,3,4,6,8,9];
arr.nextCons(); // 1
arr.nextCons(); // 6
arr.nextCons();‚Äč // 8