假设有一个数组是这样[{eid:cat,name:aa},{eid:cat,name:bb},{eid:dog,name:cc},{eid:cat,name:dd},{eid:pig,name:ee},{eid:cat,name:ff},{eid:dog,name:gg}]我想要对数组做处理,将相同的eid放在一起变成[{eid:cat,name:aa},{eid:cat,name:bb},{eid:cat,name:dd},{eid:cat,name:ff},{eid:dog,name:cc},{eid:dog,name:gg},{eid:pig,name:ee}]这有办法实现吗?
2 回答
慕婉清6462132
TA贡献1804条经验 获得超2个赞
vardata=[{eid:'cat',name:'aa'},{eid:'cat',name:'bb'},{eid:'dog',name:'cc'},{eid:'cat',name:'dd'},{eid:'pig',name:'ee'},{eid:'cat',name:'ff'},{eid:'dog',name:'gg'}]functiontrans(data){letcache={}//cache存储的键是eid,值是这个eid在indices数组中的下标letindices=[]//数组中的每一个值是一个数组,数组中的每一个元素是原数组中相同eid的下标data.forEach((item,i)=>{leteid=item.eidletindex=cache[eid]if(index!==undefined){indices[index].push(i)}else{cache[eid]=indices.lengthindices.push([i])}})/***此时,cache:{cat:0,dog:1,pig:2}*indices:[[0,1,3,5],[2,6],[4]]*indices中的第1项是eid为cat的数组下标*indices中的第2项是eid为dog的数组下标*indices中的第3项是eid为pig的数组下标*/letresult=[]indices.forEach(item=>{item.forEach(index=>{result.push(data[index])//依次把index对应的元素data[index]添加进去即可})})returnresult}letresult=trans(data)console.log(result)你的问题里面有个不明确的地方,比如下面这个例子:vardata=[{eid:'dog',name:'aa'},{eid:'cat',name:'bb'},{eid:'dog',name:'cc'}]你是想输出1:[{eid:'dog',name:'aa'},{eid:'dog',name:'cc'},{eid:'cat',name:'bb'}]还是想输出2:[{eid:'cat',name:'bb'},{eid:'dog',name:'aa'},{eid:'dog',name:'cc'}]输出1是按照出现的先后顺序排列的,输出2是按照字母序排列的,我给的是输出1的函数,如果想要输出2的结果,可以参考楼上。
添加回答
举报
0/150
提交
取消