Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Iterating through an array, adding occurrences of a true in JavaScript
Suppose we have an array of true/false values 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']; console.log(arr);
[ 'f', 't', 'f', 't', 't', 't', 'f', 'f', 't', 't', 't', 't', 't', 't', 'f', 't' ]
We need to count consecutive occurrences of 't' that are sandwiched between two 'f's and return an array of those counts.
Example
Here's how to count consecutive 't' values between 'f's:
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));
[ 1, 3, 6, 1 ]
How It Works
The algorithm uses a reduce function that:
- Starts with an accumulator
[0] - When it encounters 't', it increments the last counter in the array
- When it encounters 'f' and the last counter is not zero, it starts a new counter by pushing 0
- This creates separate counts for each cluster of 't's between 'f's
Alternative Approach
Here's a more readable approach using a simple loop:
const arr = ['f', 't', 'f', 't', 't', 't', 'f', 'f', 't', 't', 't', 't', 't', 't', 'f', 't'];
const countClustersSimple = (arr) => {
const result = [];
let count = 0;
for (let i = 0; i 0) {
result.push(count);
count = 0;
}
}
return result;
};
console.log(countClustersSimple(arr));
[ 1, 3, 6, 1 ]
Conclusion
Both approaches effectively count consecutive 't' values between 'f's. The reduce method is more functional, while the loop approach is more straightforward and easier to understand.
Advertisements
