The most efficient way would be to write a custom function, but the easiest way would be to use Lodash's groupBy
import { groupBy } from 'lodash'
const arr = [
{
category: 'Food',
name: 'Some food1'
},
{
category: 'Food',
name: 'Some food2'
},
]
const groups = groupBy(arr, 'category')
// returns {
// Food: [
// { category: 'Food', name: 'Some food1' },
// { category: 'Food', name: 'Some food2' },
// ]
// }
const groupedArr = Object.entries(groups).map(([title, items]) => ({ title, items }))
// returns [
// {
// title: 'Food',
// items: [
// { category: 'Food', name: 'Some food1' },
// { category: 'Food', name: 'Some food2' },
// ]
// },
// ]
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…