Search code examples
javascriptarraysfind-occurrences

JavaScript: Print character with number of uninterrupted occurrences for each sequence of characters


This is not a duplicate of Counting the occurrences / frequency of array elements There are differences.

I've got an array with chars:

const data = ['a', 'a', 'b', 'x', 'x', 'x', 'a'];

I need to count each sequence of characters and print character with number of uninterrupted occurrences like this (each line should log after program finds uninterrupted occurrences:

a: 2
b: 1
x: 3
a: 1

I thought to use 'while' but I'm stuck a little bit on this logic.

const countSeq = (arr) => {

  while (arr.length > 0) {

    // logic there

    console.log(/*char: count number*/);

    if (arr.length === 0) break;

  }

}

Sorry for bothering, I'm just learning. Thanks in advance!


Solution

  • const data = ['a', 'a', 'b', 'x', 'x', 'x', 'a'];
    
    const result = data.reduce((acc, val) => {
        const prevSeq = acc[acc.length - 1];
    
        if (!prevSeq || prevSeq.key !== val) {
            acc.push({ key: val, count: 1 });
        } else {
            prevSeq.count++;
        }
    
        return acc;
    }, []);
    
    console.log(result);