1 回答

TA貢獻(xiàn)1818條經(jīng)驗 獲得超11個贊
我把名字分組,然后數(shù)數(shù)。
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)
添加回答
舉報