js数组如何分组?

[{
        "departmentName": "检验室(Lab Test)",
        "queueTotalNumber": 3,
        "personnelList": [{
            "departmentName": "检验室(Lab Test)",
            "medicalPersonnelName": "张其",
            "departmentId": "05",
            "clinicNo": "检验室001",
            "queueNo": "2007"
        }, {
            "departmentName": "检验室(Lab Test)",
            "medicalPersonnelName": "张刘",
            "departmentId": "05",
            "queueNo": "2006"
        }, {
            "departmentName": "检验室(Lab Test)",
            "medicalPersonnelName": "张捌",
            "departmentId": "05",
            "queueNo": "2008"
        }, {
            "departmentName": "检验室(Lab Test)",
            "medicalPersonnelName": "李叁",
            "departmentId": "05",
            "queueNo": "2012"
        }],
        "departmentId": "05"
    }, {
        "departmentName": "五官科 (EENT)",
        "queueTotalNumber": 0,
        "personnelList": [],
        "departmentId": "06"
    }, {
        "departmentName": "妇科",
        "queueTotalNumber": 0,
        "personnelList": [],
        "departmentId": "08"
    }, {
        "departmentName": "妇科1",
        "queueTotalNumber": 0,
        "personnelList": [],
        "departmentId": "08"
    }, {
        "departmentName": "妇科2",
        "queueTotalNumber": 0,
        "personnelList": [],
        "departmentId": "08"
    }]

如何把上面的第一层数据每2个分组,第二层数据personnelList 每2个分组

回复
阅读 1.6k
4 个回答

loadsh 的chunk方法,可以试试:https://www.lodashjs.com/docs...

_.chunk(
arr.map(item => ({
    ...item,
    personnelList: _.chunk(item.personnelList, 2)
})),
2)

这样应该就可以了,优化我就不帮你优化了。

data.reduce((pv, cv, i)=>{
    // 计算组数量
    pv[Math.floor(i / 2)] = pv[Math.floor(i / 2)] || []
    pv[Math.floor(i / 2)].push(cv);
    cv.personnelList2 = cv.personnelList.reduce((pv,cv,i)=>{
        // 计算组数量 同上
        pv[Math.floor(i / 2)] = pv[Math.floor(i / 2)] || []
        pv[Math.floor(i / 2)].push(cv);
        return pv;
    },[])
    return pv;
}, [])
function groupFixLength(list, len, cb) {
  return list.reduce((res, v) => {
    const pre = res[res.length-1]
    if(pre && pre.length < len) pre.push(v)
    else res.push([v])
    cb && cb(v)
    return res
  },[])
}
groupFixLength(data, 2, v => v.personnelList = groupFixLength(v.personnelList, 2))
const getResInterval2 = (data) => {
  const baseInterval2 = (arr) => {
    const res = []
    for (let i = 0; i < arr.length; i += 2) {
      const t = arr[i + 1] ? [arr[i], arr[i + 1]] : [arr[i]]
      res.push(t)
    }
    return res
  }
  for (let i = 0; i < data.length; i++) {
    data[i].personnelList = baseInterval2(data[i].personnelList)
  }
  return baseInterval2(data)
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏