Abhay Desai
Abhay Desai

Reputation: 253

How to verify whether an array members are consecutive or not?

How can I verify whether array members are "continuous" or not?

As an example, Array [1,3,4,5,6] is not a continuous array as it is missing number 2 in between which will complete the increasing order sequence. Which JavaScript array methods can be a good candidate for this kind of validation?

I have tried JavaScript array methods such as ".map", ".every", ".some", but with no luck.

   let values = [1,3,4,5,6];

   let result1 = values.map(x => x > 5);
   console.log('value of result1 : ', result1);
   Result: "value of result1 : ", [false, false, false, false, true]

   let result2 = values.some(x => x > 5);
   console.log('value of result2 : ', result2);
   Result: "value of result2 : ", true
   
   let result5 = values.every(x => x > 4);
   console.log('value of result5 : ', result5);
   Result: "value of result5 : ", false

Thanks...

Upvotes: 1

Views: 244

Answers (5)

Nathan Getachew
Nathan Getachew

Reputation: 789

A simple loop can also help.

function continuos(arr) {
  let prev = arr[0];
  for (var i = 1; i < arr.length - 1; i++) {
    if (prev + 1 !== arr[i]) return false;
    prev = arr[i];
  }
  return true;
}

let values = [1, 3, 4, 5, 6];
console.log(continuos(values));

Upvotes: 1

xehpuk
xehpuk

Reputation: 8241

This should be fast and easy to understand:

const isConsecutive = (array) => {
  for (let i = 1; i < array.length; i++) {
    if (array[i] !== array[i - 1] + 1) {
      return false
    }
  }
  return true
}

We start at index 1 and compare the current element with the previous.

Upvotes: 1

Rubydesic
Rubydesic

Reputation: 3476

A solution using reduce just for fun, don't use this in your actual codebase or the next person to come along will want to gouge your eyes out.

const increasing = arr.reduce(([p, v], c) => ([c, (c >= p) && v]), [arr[0], true])[1]

Upvotes: 0

Renato Sant&#39;Anna
Renato Sant&#39;Anna

Reputation: 458

Use the function every with of as code:

values.every((num, i) => i === values.length - 1 || num === values[i + 1] -1 )

let values = [1,3,4,5,6];
console.log(values.every((num, i) => i === values.length - 1 || num === values[i + 1] -1 ));

Upvotes: 2

Aplet123
Aplet123

Reputation: 35512

slice then use some, utilizing the fact that the index is passed as the second argument:

values.slice(1).some((v, i) => v != values[i] + 1)

Upvotes: 0

Related Questions