DISABLE ADBLOCK

ADBlock is blocking some content on the site

ADBlock errore
Results found: 

Question

JavaScript to check consecutive numbers in array?

JavascriptWeb DevelopmentObject Oriented Programming

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
raja
Published on 10-Sep-2020 10:42:47
Advertisements

If you like, leave us your opinion

Was the article helpful and is it translated correctly?

Not affiliated with Tutorialspoint