- Trending Categories
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
Counting the clusters of positive numbers - JavaScript Arrays
Let’s say, 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 non-negative (positives and 0) numbers in the array.
Like here we have consecutive non-negatives from index 3 to 3 (only one element, but still a cluster) which forms one group and then from 9 to end of array forms the second group.
Therefore, for this array, the function should return 2.
Example
Following is the code −
const arr = [-1,-2,-1,0,-1,-2,-1,-2,-1,0,1,0]; const positiveClusters = arr => { return arr.reduce((acc, val, ind) => { if(val >= 0 && (arr[ind+1] < 0 || typeof arr[ind+1] === 'undefined')){ acc++; }; return acc; }, 0); }; console.log(positiveClusters(arr));
Output
This will produce the following output in console −
2
Advertisements