let groups = {}
array.forEach(function (o) {
var group = JSON.stringify(f(o))
groups[group] = groups[group] || []
groups[group].push(o)
})
return Object.keys(groups).map(function (group) {
return groups[group]
})
}
const arrayGroupBy = (list, groupId) =>{
let sorted = groupBy(list, function (item) {
return [item[groupId]]
})
return sorted
}
arrayGroupBy(数组, '字段名称')
若后台返回格式如下:
let data = [
{"createdAt": "2020-08-02T11:00:24.580Z", "name": "西瓜"},
{"createdAt": "2020-08-03T11:00:24.580Z", "name": "水蜜桃"},
{"createdAt": "2020-08-03T11:00:24.580Z", "name": "樱桃"},
{"createdAt": "2020-08-02T11:00:24.580Z", "name": "西柚"},
]
方法:使用 dayjs(createdAt).format('YYYY-MM-DD') 转换
注:dayjs 安装引用
npm install dayjs --save import dayjs from 'dayjs'
for ( let i=0i<array.lengthi++ ) {
let createdAt = dayjs(array[i].time)
array[i].createdAt = createdAt
}
mapName (array) {
let newArray = []
array.forEach((item, i) =>{
let index = -1
let alreadyExists = newArray.some((newItem, j) =>{
if (item.createdAt === newItem.createdAt) {
index = j
return true
}
})
if (!alreadyExists) {
newArray.push({
createdAt: item.createdAt,
name: [item.name]
})
} else {
newArray[index].price.push(item.name)
}
})
return newArray
}