2

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)
4
  • 1
    Your object inside array is not valid for your task and look like [{ value: "4" }] Commented Jul 21, 2020 at 7:15
  • 2
    The array you posted contains only one item: an invalid object. An object cannot have multiple keys having the same name. Commented Jul 21, 2020 at 7:17
  • Sorrry, I have edited Commented Jul 21, 2020 at 7:18
  • can u help me now ? Commented Jul 21, 2020 at 7:22

5 Answers 5

3

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"}])
)

Sign up to request clarification or add additional context in comments.

5 Comments

This won't work for empty array or single array item, as well as descending order (OP didn't state whether this is the case, though).
@YevhenHorbunkov "every" returns true for an empty array
@FernandoFlores: the point being made was that the empty array unlikely qualifies as an array of consecutive numbers.
@YevhenHorbunkov I don't think so... Do you know about the vacuous truth?
@YevhenHorbunkov This was not the input provided in the question and can easily be fixed by adding a length check. The goal of these answers is to guide the OP in the right direction. There could be many edge cases where the source is empty, or null, or undefined, or the nested object doesn't have value property etc
2

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' }]));

2 Comments

This will fail for a single item in array or empty array and won't work for descending order (OP didn't state whether this is the case, though).
@YavuzSelimÖzmen : while above solution fails for the whole bunch of edge cases just like .every()-based method, the former works much slower as it will loop throughout the entire array, whereas .every() exits upon first non-consecutive value
0

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")
}

Comments

0

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.

Comments

-1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.