Iterating through an array, adding occurrences of a true in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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 ]
raja
Published on 21-Nov-2020 10:10:22
Advertisements