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