Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
JavaScript to check consecutive numbers in array?
To check for consecutive numbers in an array, you can use JavaScript's reduce() method or simpler approaches. This returns true for consecutive sequences like 100, 101, 102, and false otherwise.
Method 1: Using reduce() with Objects
This approach works with arrays of objects containing number properties:
const sequenceIsConsecutive = (obj) =>
Boolean(obj.reduce((output, latest) => (output ?
(Number(output.number) + 1 === Number(latest.number) ? latest : false)
: false)));
console.log("Is Consecutive = " + sequenceIsConsecutive([
{ number: '100' },
{ number: '101' },
{ number: '102' }
]));
console.log("Is Consecutive = " + sequenceIsConsecutive([
{ number: '100' },
{ number: '102' },
{ number: '104' }
]));
Is Consecutive = true Is Consecutive = false
Method 2: Simple Array of Numbers
For basic arrays of numbers, this simpler approach is more readable:
function isConsecutive(arr) {
if (arr.length
Is Consecutive = true
Is Consecutive = false
Is Consecutive = true
Method 3: Using every() Method
The every() method provides another clean solution:
function checkConsecutive(arr) {
return arr.every((num, index) =>
index === 0 || num === arr[index - 1] + 1
);
}
console.log("Is Consecutive = " + checkConsecutive([1, 2, 3, 4]));
console.log("Is Consecutive = " + checkConsecutive([10, 12, 14]));
console.log("Is Consecutive = " + checkConsecutive([50, 51, 52, 53]));
Is Consecutive = true
Is Consecutive = false
Is Consecutive = true
Comparison
| Method | Data Type | Readability | Performance |
|---|---|---|---|
| reduce() with objects | Array of objects | Complex | Good |
| Simple loop | Array of numbers | High | Best |
| every() method | Array of numbers | High | Good |
Conclusion
Use the simple loop approach for basic number arrays, or every() for a functional programming style. The reduce() method works well with complex object structures.
Advertisements
