
- 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
Grouping of same kind of numbers 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 nonnegative (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.
So, for this array, the function should return 2.
Therefore, let’s write the code for this function −
Example
The code for this will be −
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
The output in the console will be −
2
- Related Articles
- Grouping array of array on the basis of elements in JavaScript
- Explain Grouping operator in JavaScript.
- Grouping array values in JavaScript
- Grouping nested array in JavaScript
- Finding special kind of sentences (smooth) in JavaScript
- Grouping on the basis of object property JavaScript
- Splitting array of numbers into two arrays with same average in JavaScript
- Complicated array grouping JavaScript
- Grouping data to monthwise in JavaScript
- Array grouping on the basis of children object’s property in JavaScript
- Add grouping specifiers for large numbers in Java
- What kind of MongoDB query finds same value multiple times in an array?
- Grouping words with their anagrams in JavaScript
- Finding special kind of elements with in an array in JavaScript
- Return the scalar type of highest precision of the same kind as the input in Python

Advertisements