为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕田峪4524236 2023-09-21 16:54:31
我有一个像这样的数组{John, John, John, Maria, Peter, Peter, Maria, Anna, Anna, Maria, Maria, Peter}我需要得到像这样的结果1 -> 32 -> 13 -> 24 -> 15 -> 26 -> 27 -> 1
查看完整描述

1 回答

?
慕尼黑8549860

TA贡献1818条经验 获得超11个赞

我把名字分组,然后数数。


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)


查看完整回答
反对 回复 2023-09-21
  • 1 回答
  • 0 关注
  • 56 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信