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
Count of pairs in an array that have consecutive numbers using JavaScript
Problem
We need to write a JavaScript function that takes an array of integers and returns the count of consecutive pairs. A consecutive pair consists of two adjacent elements in the array where one number is exactly one more than the other.
Understanding Consecutive Pairs
Two numbers are consecutive if their absolute difference is 1. For example, (5, 6), (8, 7), and (-3, -4) are all consecutive pairs.
Solution
We'll iterate through the array in steps of 2, treating each pair of adjacent elements as a potential consecutive pair:
const arr = [1, 2, 5, 8, -4, -3, 7, 6, 5];
const countPairs = (arr = []) => {
let count = 0;
for (var i = 0; i
3
How It Works
The function checks pairs at positions (0,1), (2,3), (4,5), etc. For each pair, it verifies if the numbers are consecutive by checking:
-
arr[i] - 1 === arr[i+1]- First number is one greater than second -
arr[i] + 1 === arr[i+1]- First number is one less than second
Step-by-Step Breakdown
const arr = [1, 2, 5, 8, -4, -3, 7, 6, 5];
// Let's trace through each pair
console.log("Pair 1: [1, 2] - Consecutive:", (1 + 1 === 2)); // true
console.log("Pair 2: [5, 8] - Consecutive:", (5 + 1 === 8 || 5 - 1 === 8)); // false
console.log("Pair 3: [-4, -3] - Consecutive:", (-4 + 1 === -3)); // true
console.log("Pair 4: [7, 6] - Consecutive:", (7 - 1 === 6)); // true
console.log("Last element [5] - No pair");
Pair 1: [1, 2] - Consecutive: true Pair 2: [5, 8] - Consecutive: false Pair 3: [-4, -3] - Consecutive: true Pair 4: [7, 6] - Consecutive: true Last element [5] - No pair
Alternative Approach: All Adjacent Pairs
If you want to count all adjacent consecutive pairs (not just at even indices), here's an alternative:
const countAllConsecutivePairs = (arr = []) => {
let count = 0;
for (let i = 0; i
All consecutive pairs: 4
Conclusion
The original solution counts consecutive pairs at even-indexed positions only, returning 3 for the given array. Use Math.abs() for a cleaner approach when checking if two numbers are consecutive.
