
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
Count of pairs in an array that have consecutive numbers using JavaScript
Problem
We are required to write a JavaScript function that takes in an array of integers. Our function should return the count of such contagious pairs from the array that have consecutive numbers in them.
Example
Following is the code −
const arr = [1, 2, 5, 8, -4, -3, 7, 6, 5]; const countPairs = (arr = []) => { let count = 0; for (var i=0; i<arr.length; i+=2){ if(arr[i] - 1 === arr[i+1] || arr[i] + 1 === arr[i + 1]){ count++; }; }; return count; }; console.log(countPairs(arr));
Output
3
- Related Articles
- Count Pairs of Consecutive Zeros in C++
- Three strictly increasing numbers (consecutive or non-consecutive). in an array in JavaScript
- JavaScript to check consecutive numbers in array?
- Count of pairs (x, y) in an array such that x < y in C++
- Count divisible pairs in an array in C++
- Removing consecutive duplicates from strings in an array using JavaScript
- Deep count of elements of an array using JavaScript
- Python program to count pairs for consecutive elements
- Maximum consecutive numbers present in an array in C++
- Count pairs in an array such that both elements has equal set bits in C++
- Count pairs in an array that hold i*arr[i] > j*arr[j] in C++
- Count pairs in an array such that at least one element is prime in C++
- Program to count nice pairs in an array in Python
- Count pairs in an array such that frequency of one is at least value of other in C++
- Using recursion to remove consecutive duplicate entries from an array in JavaScript

Advertisements