- Related Questions & Answers
- 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++
- Sum of consecutive numbers in JavaScript
- Count divisible pairs in an array in C++
- Count the number of pairs that have column sum greater than row sum in C++
- Deep count of elements of an array using JavaScript
- Maximum consecutive numbers present in an array in C++
- Removing consecutive duplicates from strings in an array using JavaScript
- Count pairs in an array such that frequency of one is at least value of other in C++
- Count pairs in an array such that both elements has equal set bits in C++
- Count pairs in an array such that at least one element is prime in C++
- Find number of pairs in an array such that their XOR is 0 using C++.
- Count of index pairs with equal elements in an array in C++

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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.

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));

3

Advertisements