
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Iterate Through Array Adding Occurrences of True in JavaScript
Suppose we have an array of true/false represented by 't'/'f' which we retrieved from some database like this −
const arr = ['f', 't', 'f', 't', 't', 't', 'f', 'f', 't', 't', 't', 't', 't', 't', 'f', 't'];
We are required to write a JavaScript function that takes in one such array. Our function should count the consecutive appearances of those 't' that are sandwiched between two 'f's and return an array of that count.
Therefore, for the above array, the output should look like −
const output = [1, 3, 6, 1];
Example
The code for this will be −
const arr = ['f', 't', 'f', 't', 't', 't', 'f', 'f', 't', 't', 't', 't', 't', 't', 'f', 't']; const countClusters = (arr = []) => { let res = []; res = arr.reduce((acc, val) => { const { length: l } = acc; if(val === 't'){ acc[l - 1]++; } else if(acc[l - 1] !== 0){ acc.push(0); }; return acc; }, [0]); return res; }; console.log(countClusters(arr));
Output
And the output in the console will be −
[ 1, 3, 6, 1 ]
Advertisements