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

javascript-仅当项目彼此相邻时,如何才能计数Java Script数组中的项目?

(javascript - 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

我有例如像这样的数组
{约翰,约翰,约翰,玛丽亚,彼得,彼得·玛丽亚·安娜,安娜玛丽亚,玛丽亚,彼得}
我需要得到这样的结果

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

我将名称分组,然后对它们进行计数。

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)