const students = [ { name: 's1', age: 22, sex: 'female' }, { name: 's2', age: 22, sex: 'male' }, { name: 's3', age: 23, sex: 'female' }, { name: 's4', age: 24, sex: 'male' }, { name: 's6', age: 21, sex: 'male' }, { name: 's5', age: 22, sex: 'female' }, { name: 's7', age: 24, sex: 'female' } ] arr = [1, 4, 2, 4, 5, 6, 5] function groupBy(arr, generateKey) { if (typeof generateKey === 'string') { const attrKey = generateKey generateKey = (item) => item[attrKey] } const result = {} arr.forEach(item => { const key = generateKey(item) if (result.hasOwnProperty(key)) { result[key].push(item) } else { result[key] = [item] } }) return result } console.log(groupBy(students, 'age')) console.log(groupBy(students, item => item.sex))
标签:name,age,sex,item,result,数组,generateKey,groupby From: https://www.cnblogs.com/howhy/p/18309868