JavaScript 使用 Array.reduce() 统计 cfList 中相同 name、age 和 sex 数据的条数
您可以使用Array.reduce()方法对cfList进行遍历,根据每条数据的name、age和sex属性进行分组,统计每组中的数据条数,并将结果赋值给patientList。同时,您可以将每条数据的id也一起存储在patientList中。以下是示例代码:\n\njavascript\nconst patientList = ref([]);\n\n// 遍历cfList,根据name、age和sex属性进行分组统计\ncfList.value.reduce((acc, curr) => {\n // 生成分组的key\n const key = `${curr.name}-${curr.age}-${curr.sex}`;\n\n // 如果分组不存在,则创建新的分组\n if (!acc[key]) {\n acc[key] = {\n count: 1,\n data: [],\n };\n } else {\n // 分组存在则累加计数\n acc[key].count++;\n } \n // 将当前数据的id保存到分组中\n acc[key].data.push(curr.id);\n\n return acc;\n}, {}).forEach((group) => {\n // 将分组转换为需要的数据格式,并添加到patientList中\n patientList.value.push({\n name: group.data[0].name,\n age: group.data[0].age,\n sex: group.data[0].sex,\n count: group.count,\n ids: group.data,\n });\n});\n\n// 输出结果\nconsole.log(patientList.value);\n\n\n请注意,上述代码假设cfList是一个ref类型的响应式数据。如果cfList不是ref类型,您可以省略value属性的使用。
原文地址: https://www.cveoy.top/t/topic/qFJw 著作权归作者所有。请勿转载和采集!