对于如下对象数组
[{id: 0, name: "name1"}, {id: 1, name: "name2"},{id: 1, name: "name2"},{id: 1, name: "name2"}, {id: 2, name: "name3"}, {id: 0, name: "name4"}]
现在想要将id相同的对象的name拼起来,笨的算法如下:
var ids = []; var ret = []; var map = {}; var arr = [{id: 0, name: "name1"}, {id: 1, name: "name2"},{id: 1, name: "name2"},{id: 1, name: "name2"}, {id: 2, name: "name3"}, {id: 0, name: "name4"}]; //循环调用 for (let i = 0; i < arr.length; i++) { map["" + arr[i].id] = arr[i]; } var mulObj = {}; var mulArr = []; for (var i = 0; i < arr.length; i++) { var obj = arr[i]; //当前对象 if (ids.indexOf(obj.id) != -1) { //如果包含,先取出该对象,然后遍历查找重复对象 mulObj = map["" + obj.id]; //重复的对象+obj已有对象-----合并 mulArr.push(mulObj); } else { ids.push(obj.id); ret.push(obj); } } for (let i = 0; i < ret.length; i++) { for(let j=0;j<mulArr.length;j++){ if(ret[i].id == mulArr[j].id){ //说明重复 ret[i].name += mulArr[j].name; } } } console.log(ret);
对于形如这种字符串或数字数组去重:
[1,2,3,4,2,6,3,2,6,6,8]
简单算法实现如下:
let ret = []; let hash = {}; for (let i = 0; i < arr.length; i++) { let item = arr[i]; let key = typeof(item) + item; if (hash[key] !== 1) { ret.push(item); hash[key] = 1; } } return ret;