如何按月份聚类两个关联数组,对重复月份对应数值求和并去重
实现方案
核心逻辑
- 先遍历两组数组的对应元素,累计每个月份的数值总和
- 可根据需求选择排序规则:按月份首次出现顺序、按月份自然时间顺序、按数值总和大小排序
- 最后拆分得到无重复月份数组和对应总和数组
代码示例(Python)
from collections import defaultdict # 输入数组 array1 = ['jan','mar','dec','jan','sep','nov','mar'] array2 = [3,5,5,4,5,8,2] sum_map = defaultdict(int) # 记录月份首次出现的顺序,保证输出顺序和输入首次出现顺序一致 month_first_order = [] for month, value in zip(array1, array2): # 累加对应月份的数值 sum_map[month] += value # 首次出现的月份加入顺序列表 if month not in month_first_order: month_first_order.append(month) # 生成目标数组 array3 = month_first_order array4 = [sum_map[month] for month in month_first_order] # 输出结果: # array3 = ['jan', 'mar', 'dec', 'sep', 'nov'] # array4 = [7, 7, 5, 5, 8]
代码示例(JavaScript)
// 输入数组 const array1 = ['jan','mar','dec','jan','sep','nov','mar'] const array2 = [3,5,5,4,5,8,2] const sumMap = {} const monthFirstOrder = [] for (let i = 0; i < array1.length; i++) { const month = array1[i] const value = array2[i] sumMap[month] = (sumMap[month] || 0) + value if (!monthFirstOrder.includes(month)) { monthFirstOrder.push(month) } } const array3 = monthFirstOrder const array4 = monthFirstOrder.map(month => sumMap[month]) // 输出结果: // array3 = ['jan', 'mar', 'dec', 'sep', 'nov'] // array4 = [7, 7, 5, 5, 8]
如果需要按照自然月份顺序排序,可添加月份映射表调整排序逻辑即可:
// 月份自然顺序映射 const monthSortMap = {jan:1, feb:2, mar:3, apr:4, may:5, jun:6, jul:7, aug:8, sep:9, oct:10, nov:11, dec:12} // 排序后的月份数组 const sortedMonths = monthFirstOrder.sort((a,b) => monthSortMap[a] - monthSortMap[b])
内容的提问来源于stack exchange,提问作者Josh
相关产品推荐
相关产品推荐

