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))
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.