1 回答
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)
添加回答
举报