- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Count groups of negatives 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];
Let’s say, we are required to write a JavaScript function that counts the consecutive groups of negative numbers in the array.
Like here we have consecutive negatives from index 0 to 2 which forms one group and then from 4 to 8 forms the second group
So, for this array, the function should return 2.
Example
Let’s write the code −
const arr = [-1,-2,-1,0,-1,-2,-1,-2,-1,0,1,0]; const countNegativeGroup = arr => { return arr.reduce((acc, val, ind) => { if(val < 0 && arr[ind+1] >= 0){ acc++; }; return acc; }, 0); }; console.log(countNegativeGroup(arr));
Output
Following is the output in the console −
2
- Related Articles
- Returning the value of (count of positive / sum of negatives) for an array in JavaScript
- Removing Negatives from Array in JavaScript
- JavaScript Algorithm - Removing Negatives from the Array
- Pushing positives and negatives to separate arrays in JavaScript
- Count unique values per groups in Python Pandas
- Given an array of integers return positives, whose equivalent negatives present in it in JavaScript
- Similar string groups in JavaScript
- Count of pairs in an array that have consecutive numbers using JavaScript
- Find groups of strictly increasing numbers in a list in Python
- Rearranging cards into groups in JavaScript
- Finding the count of total upside down numbers in a range using JavaScript
- Split string into groups - JavaScript
- Splitting string into groups – JavaScript
- Splitting an array into groups in JavaScript
- Reduce an array to groups in JavaScript

Advertisements