-1

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!

a1tern4tive
  • 422
  • 3
  • 11
  • @a1tern4tive that was not my intent - i genuinely want to help if you have something specific about where you get stuck. you'll learn best if you push yourself – Daniel A. White Jun 16 '20 at 14:00

1 Answers1

1

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);
Nikita Madeev
  • 4,284
  • 9
  • 20