Check consecutive numbers in array javascript

There is a array like this on my hand;

var array = [{value:"0"},{value:"1"},{value:"2"},{value:"3"},{value:"4"}];

I need check, this numbers is going consecutive?

[{value:"0"},{value:"1"},{value:"2"},{value:"3"},{value:"4"}];
TRUE (0,1,2,3,4)

[{value:"0"},{value:"1"},{value:"2"},{value:"3"},{value:"5"}];
FALSE (0,1,2,3,5)

Upvotes: 2

Views: 2139

Answers (5)

Firmin Martin
Firmin Martin

Reputation: 308

Here is an auxiliary function that computes the length of the most long subarray of an array.

const maxConsecutive = (arr) => {
    const result = arr.reduce((a, b) => {
        const { count, maxCount, cons } = a;
        if (cons.length === 0)
            return { count: 1, maxCount: Math.max(1, maxCount), cons: cons.concat([b]) };
        else {
            const last = cons.at(-1);
            const isCons = (b - last) === 1;
            return {
                count: isCons ? count + 1 : 0,
                maxCount: isCons ? Math.max(count + 1, maxCount) : maxCount,
                cons: isCons ? cons.concat([b]) : []
            };
        }
    }, { count: 0, maxCount: 0, cons: [] });
    return result.maxCount;
}

Sample outputs:

maxConsecutive([])
> 0
maxConsecutive([0,1,2,3,4])
> 5
maxConsecutive([0,1,2,3,5])
> 4

So now, it's pretty obvious how it can be helpful to check whether the array is consecutive or not: it suffices to maxConsecutive(arr) === arr.length.

Upvotes: 0

Tom
Tom

Reputation: 1030

The other answer are really well made, and look very pleasing. However as @Yevgen Gorbunkov mentioned, they do not take empty arrays, single item arrays, as well as desc order.

I am quite new to JS so the answer is not optimal and can most likely be improved. But I figured giving it a shot wouldn't hurt.

Attempt 1: jsfiddle

//var arrr = [{value:"0"}];
var arrr = [{value:"8"},{value:"7"},{value:"6"},{value:"5"},{value:"4"},{value:"3"},{value:"2"},{value:"1"},{value:"0"}];
//var arrr = [{value:"8"},{value:"3"},{value:"6"},{value:"5"},{value:"4"},{value:"3"},{value:"2"},{value:"1"},{value:"0"}];
//var arrr = [];
//var arrr = [{value:"0"},{value:"1"},{value:"2"},{value:"3"},{value:"4"},{value:"5"},{value:"6"},{value:"7"},{value:"8"}];

var arr = arrr.map(function (obj) {
  return Number(obj.value);
});

isConsecutive(arr);
 
 function isConsecutive(arr) {
 
  var consecutive;
  let previousAsc = arr[0];
  let previousDesc = arr[0];
  let firstAsc;
  let firstDesc;
  
  for (let i = 1; i < arr.length; i++) {
    if ((previousDesc - 1) !== arr[i]) {
      if ((previousAsc + 1) !== arr[i]) {
        firstAsc = arr[i];
        consecutive = false;
        break;
      } else {
        consecutive = true;
            previousDesc --;
            previousAsc ++;
      }
    
    } else {
            consecutive = true;
            previousDesc --;
            previousAsc ++;
    }
  }
  console.log(consecutive)
}

Attempt 2: jsfiddle

//var arrr = [{value:"0"}];
var arrr = [{value:"8"},{value:"7"},{value:"6"},{value:"5"},{value:"4"},{value:"3"},{value:"2"},{value:"1"},{value:"0"}];
//var arrr = [{value:"8"},{value:"3"},{value:"6"},{value:"5"},{value:"4"},{value:"3"},{value:"2"},{value:"1"},{value:"0"}];
//var arrr = [];
//var arrr = [{value:"0"},{value:"1"},{value:"2"},{value:"3"},{value:"4"},{value:"5"},{value:"6"},{value:"7"},{value:"8"}];

var arr = arrr.map(function (obj) {
  return Number(obj.value);
});
var arrSort = arrr.map(function (obj) {
  return Number(obj.value);
});

if(arr && arr.length >= 2){

  if(JSON.stringify(arrSort.sort()) === JSON.stringify(arr) || JSON.stringify(arrSort.sort().reverse()) === JSON.stringify(arr)){
    /* console.log(arrSort.sort().reverse());
        console.log(arr); */
    console.log("Array is consecutive")
  } else {
    /* console.log(arrSort.sort());
        console.log(arr); */
    console.log("Array is not consecutive")
  }
} else {
    console.log("array does not exist or does not have enough values to start")
}

Upvotes: 0

crazy_phage
crazy_phage

Reputation: 548

Here is another way to to this.

const array = [{value:"0"},{value:"1"},{value:"2"},{value:"3"},{value:"4"}];

function isConsecutive (array) {
    const pred = array.map (i => parseInt(i.value))
    const expect = range(0, 4) // maybe use lodash.
    return pred === expect 
}

I think you do know what numbers are consecutive, so you can create a consecutive array to match your original input.

Upvotes: -1

adiga
adiga

Reputation: 35222

You could check if every item is one more than the previous item. This will stop looping once a non-consecutive values is found

array.every(({ value }, i) => i === 0 || +value === +array[i-1].value + 1)

Here's a snippet:

function isConsecutive(array) {
  return array.every(({ value }, i) => i === 0 || +value === +array[i-1].value + 1)
}

console.log(
  isConsecutive([{value:"0"},{value:"1"},{value:"2"},{value:"3"},{value:"4"}]),
  isConsecutive([{value:"0"},{value:"1"},{value:"3"}])
)

Upvotes: 3

Nikita Madeev
Nikita Madeev

Reputation: 4380

You can use reduce with the initial value as the first element of the array

const checkIsConsecutive = (array) =>
    Boolean(array.reduce((res, cur) => (res ? (Number(res.value) + 1 === Number(cur.value) ? cur : false) : false)));

console.log(checkIsConsecutive([{ value: '0' }, { value: '1' }, { value: '2' }, { value: '3' }, { value: '4' }]));
console.log(checkIsConsecutive([{ value: '0' }, { value: '1' }, { value: '2' }, { value: '3' }, { value: '5' }]));

Upvotes: 2

Related Questions