不同属性的对象数组的合并(好吧 表述的不好

来源:互联网 发布:西门子s7200编程手册 编辑:程序博客网 时间:2024/04/29 04:51

两个list
一个叫做list1一个叫做list2
list1是一个数组,里面有很多对象,对象有很多属性,其中一个thedate属性表示这个对象是哪一天的数据
list2也是一个数组,里面有很多对象,对象也有很多属性,除了thedate属性以外,其他属性和list1中不同
现在要把list1和2中thedate一样的对象各种属性合在一起,不同的就和空的合在一起
比如:
list1[
0{
a:1,
b:2
thedate:2016-11-01
},1{
a:3,
b:8
thedate:2016-11-05
},2{
a:5,
b:1
thedate:2016-11-08
}
]

list2[
0{
c:1,
d:3
thedate:2016-11-03
},1{
c:4,
d:3
thedate:2016-11-04
},2{
c:8,
d:0
thedate:2016-11-05
}
]

想要的是
[
0{
a:1,
b:2
thedate:2016-11-01
},1{
c:1,
d:3
thedate:2016-11-03
},2{
c:4,
d:3
thedate:2016-11-04
},3{
a:3,
b:8
c:8,
d:0
thedate:2016-11-05
},4{
a:5,
b:1
thedate:2016-11-08
}
]

怎么合并很麻烦
有一个比较暴力的方法就是对于1中的每一个去2中匹配,thedate相同的就拼一起,1中有,2没有的就把1自己和空合在一起,然后想办法把2中被剩下的(2有1没有的)push进去,然后把新数组按照时间排序
这样需要n的平方+n的时间复杂度

然后我结合自己以前做过的算法想了一个办法
哈希的思想形成一个以thedate作为key的map,原来是以01234作为key的
比如,把list1先形成一个map,以thedate为key:
listmap[
2016-11-01{……},
2016-11-05{……},
2016-11-08{……}
]

2016-11-012016-11-022016-11-032016-11-042016-11-052016-11-062016-11-072016-11-08√---√--√

查询2中的每一个数据的thedate 查到以后去查listmap[thedate]的值,如果是有数据就合并(见上一篇博客)
如果没有数据就让listmap[thedate]=list2中这个数据
然后listmap就是一个合并完全的数组
但是还有一个问题就是listmap的key是日期,而不是01234
传到chart中需要01234
因此遍历map 将他们一个个push到list中去
然后将list按照日期排序

怎么按照日期排序呢?、
list.sort(function (a,b) {//按照日期排序
a = a[‘thedate’]; a = new Date(Date.parse( a.replace(/-/g, “/”)));
b = b[‘thedate’]; b = new Date(Date.parse( b.replace(/-/g, “/”)));
return b.getTime()-a.getTime();
});

哈哈哈 搞定

0 0
原创粉丝点击