Skip to content
Advertisement

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

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

Advertisement

Answer

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)
Advertisement