两个数组合并去重
应用场景:
有一个对象,该对象下有两个数组:把这两个数组展示在柱状图上,
但是这两个数组的nam列不同,但是只有一个横坐标,所以需要把两个数组的name属性合并在一个数组中:
var graphList = {
guestList:[
{name:'A1',number:12},
{name:'A2',number:112},
],
guestListCompared: [
{name:'A1',number:13},
{name:'A44',number:32},
{name:'A32',number:132},
]
};
把这个两个数组合并成两个数组,这两个数组的长度和name 顺序相同:
这样:
没有值的用-代替
list: [
{name:'A1',number:12},
{name:'A2',number:112},
{name:'A44',number:-},
{name:'A32',number:-},
];
compareList: [
{name:'A1',number:13},
{name:'A2',number:-},
{name:'A44',number:32},
{name:'A32',number:132},
];
用于下列图:
for(let one of this.graphList.guestList){ //把数组guestList 的name push到commonXlist中
commonXList.push(one.name)
}
for(let one of this.graphList.guestListCompared){ //把数组guestListCompared的name push到commonXlist中
commonXList.push(one.name)
}
commonXList =[...new Set(commonXList)]; // 去重
let list =Array(commonXList.length).fill('-') // 给数组每一项填充 ‘-’
let compareList =Array(commonXList.length).fill('-')
for(let one of this.graphList.guestList){ // 遍历guestList
let index = commonXList.indexOf(one.name); // 如果commonXList中有guestList 中的name
list[index] = one.number // 就把对应的值复制给对应的位置
}
for(let one of this.graphList.guestListCompared){
let index = commonXList.indexOf(one.name);
compareList[index] = one.number
}
最后得到两个新的数组,他们的长度和name顺序相同;