- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Finding clusters of consecutive negative integers in JavaScript
We have an array of numbers like this −
const arr = [-1,-2,-1,0,-1,-2,-1,-2,-1,0,1,0];
We are required to write a JavaScript function that counts the consecutive groups of negative numbers in the array.
Example
The code for this will be −
const arr = [-1,-2,-1,0,-1,-2,-1,-2,-1,0,1,0]; const countClusters = arr => { return arr.reduce((acc, val, ind) => { if(val < 0 && arr[ind+1] >= 0){ acc++; }; return acc; }, 0); }; console.log(countClusters(arr));
Output
The output in the console −
2
Advertisements
To Continue Learning Please Login
Login with Google