如何补全年度销量对象数组的缺失品牌以实现对比图表绘制
补全年度品牌销量数组以绘制对比图表
问题背景
要绘制品牌年度销量对比图表,但现有2020年(last_year)和2021年(current_year)的销量数组存在品牌缺失,导致图表无法正常绘制。需补全两个数组中的缺失品牌,缺失品牌的total设为0,年份对应正确。
原始数据
var current_year = [ { total: 12941.17, comapanyName: "Samsung", year: "2021" }, { total: 17946.87, comapanyName: "Haier", year: "2021" }, { total: 3832.36, comapanyName: "Beetel", year: "2021" }, { total: 12528, comapanyName: "Celkon", year: "2021" } ]; var last_year = [ { total: 427805.51, comapanyName: "Samsung", year: "2020" }, { total: 77576.33, comapanyName: "Godrej", year: "2020" }, { total: 53389.02, comapanyName: "Beetel", year: "2020" }, { total: 100748.49, comapanyName: "Celkon", year: "2020" }, { total: 4534.19, comapanyName: "FORD", year: "2020" }, { total: 5.05, comapanyName: "Voltas", year: "2020" } ];
补全方案
按照要求执行以下两个补全操作:
- 给
current_year添加last_year中存在但current_year缺失的FORD,total设为0,年份为2021 - 给
last_year添加current_year中存在但last_year缺失的Haier,total设为0,年份为2020
补全后的数据
// 补全后的2021年数据 var current_year = [ { total: 12941.17, comapanyName: "Samsung", year: "2021" }, { total: 17946.87, comapanyName: "Haier", year: "2021" }, { total: 3832.36, comapanyName: "Beetel", year: "2021" }, { total: 12528, comapanyName: "Celkon", year: "2021" }, { total: 0, comapanyName: 'FORD', year: '2021' } ]; // 补全后的2020年数据 var last_year = [ { total: 427805.51, comapanyName: "Samsung", year: "2020" }, { total: 77576.33, comapanyName: "Godrej", year: "2020" }, { total: 53389.02, comapanyName: "Beetel", year: "2020" }, { total: 100748.49, comapanyName: "Celkon", year: "2020" }, { total: 4534.19, comapanyName: "FORD", year: "2020" }, { total: 5.05, comapanyName: "Voltas", year: "2020" }, { total: 0, comapanyName: "Haier", year: "2020" } ];
通用补全逻辑(可选)
如果后续有更多品牌增减,可通过通用函数自动补全,避免手动操作:
// 获取数组中所有品牌名称 function getBrandNames(arr) { return arr.map(item => item.comapanyName); } // 补全数组缺失品牌 function completeMissingBrands(targetArr, sourceArr, targetYear) { const targetBrands = getBrandNames(targetArr); sourceArr.forEach(item => { if (!targetBrands.includes(item.comapanyName)) { targetArr.push({ total: 0, comapanyName: item.comapanyName, year: targetYear }); } }); } // 执行补全 completeMissingBrands(current_year, last_year, "2021"); completeMissingBrands(last_year, current_year, "2020");
内容的提问来源于stack exchange,提问作者Omkarok
相关产品推荐
相关产品推荐

