我有两个对象数组,如下所示:
var b = [{"from":2,"to":7,"id":1},{"from":3,"to":9,"id":2},{"from":2,"to":7,"id":3}]
var c = [{"from":3,"to":9,"id":2,"style":""},{"from":2,"to":7,"id":3,"style":"dash-line"},{"from":4,"to":2,"id":4,"style":"dash-line"},{"from":2,"to":4,"id":5,"style":""},{"from":4,"to":2,"id":6,"style":"dash-line"}];
我想要的是一个来自上面两个的对象数组,它具有唯一的"来自" "至"和"风格"应该是""(空白)或undefined。具有唯一ID。
即
output = [{"from":2,"to":7,"id":0},{"from":3,"to":9,"id":1},{"from":2,"to":4,"id":6,"style":""}]
我能够得到它,如下面的代码所示,但我觉得代码可以优化或有更好的方法来做到这一点。请帮帮....谢谢。
var b = [{"from":2,"to":7,"id":1},{"from":3,"to":9,"id":2},{"from":2,"to":7,"id":3}]
var c = [{"from":3,"to":9,"id":2,"style":""},{"from":2,"to":7,"id":3,"style":"dash-line"},{"from":4,"to":2,"id":4,"style":"dash-line"},{"from":2,"to":4,"id":5,"style":""},{"from":4,"to":2,"id":6,"style":"dash-line"}];
var a = b.concat(c);
findUniQue(a);
function findUniQue(a){
var tempArr =[];
for(var i =0;i<a.length;i++){
if(a[i].style == undefined || a[i].style != 'dash-line' ){
var count = 0;
if(tempArr.length>0){
for(var j =0;j<tempArr.length;j++){
if((a[i].from == tempArr[j].from)&&(a[i].to == tempArr[j].to)){
count--;
break;
}
else{
count++;
}
if(count == tempArr.length){
a[i].id = i;
tempArr.push(a[i]);
}
}
}
else{
a[i].id = i;
tempArr.push(a[i]);
}
}
}
console.dir(tempArr);
}
答案 0 :(得分:1)
function removeduplicate(){
var array = [{id:5},{id:8},{id:9},{id:10},{id:5},{id:8}];
var size = array.length;
for (var i = 0; i < size - 1; i++) {
for (var j = i + 1; j < size; j++) {
if (array[j].id !== array[i].id)
continue;
array.splice(j,1);
j--;
size--;
} // for j
} // for i
console.log(array);
}