JavaScript to check consecutive numbers in array?


To check for consecutive numbers like 100, 101, 102, etc., use the concept of reduce(). TRUE would be returned for consecutive numbers, else false is the return value.

Example

const sequceIsConsecutive = (obj) =>
Boolean(obj.reduce((output, lastest) => (output ?
(Number(output.number) + 1=== Number(lastest.number) ? lastest : false)
: false)));
console.log("Is Consecutive="+sequceIsConsecutive ([{ number: '100'
},{number: '101'} ,{number: '102' }]));
console.log("Is Consecutive="+sequceIsConsecutive([{ number: '100' },
{number: '102'} ,{number: '104' }]));

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo126.js.

Output

This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo126.js
Is Consecutive=true
Is Consecutive=false

Updated on: 10-Sep-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements