- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements