Warm tip: This article is reproduced from serverfault.com, please click

How can I count items in Java Script array but only when items are the same next to each other?

发布于 2020-11-30 14:26:49

I have an array for example like this
{John, John, John, Maria, Peter, Peter, Maria, Anna, Anna, Maria, Maria, Peter}
I need to get result like

1 -> 3
2 -> 1
3 -> 2
4 -> 1
5 -> 2
6 -> 2
7 -> 1

Questioner
Patrik Michnac
Viewed
0
Someone Special 2020-11-30 22:47:48

I group the names, then I count them.

const array = ['John', 'John', 'John', 'Maria', 'Peter', 'Peter', 'Maria', 'Anna', 'Anna', 'Maria', 'Maria', 'Peter'];

let final = [];
const count = array.forEach(item => {
                   //check whether the last item in the array has the same name
                   if ( final[final.length - 1] && final[final.length-1][0] === item ) {
                        final[final.length -1].push(item)
                   } else {
                        //if different name then create a new grouping
                        final[final.length] = [item]
                   }
})
console.log(final.map(item => item.length)) //returns the size of each group
console.log('final array', final)