简体   繁体   English

如何计算 Java 脚本数组中的项目,但仅当项目彼此相邻时?

[英]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 1 -> 3
2 -> 1 2 -> 1
3 -> 2 3 -> 2
4 -> 1 4 -> 1
5 -> 2 5 -> 2
6 -> 2 6 -> 2
7 -> 1 7 -> 1

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM