[英]finding unique values from two arrays of objects based on two keys i.e from and to in javascript
i have two arrays of objects like shown below : 我有两个对象数组,如下所示:
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"}];
what i want is an array of objects from above two , which has unique "from" ,"to" and "style" should be either ""(blank) or undefined.With unique ids. 我想要的是两个以上对象的数组,它们具有唯一的“ from”,“ to”和“ style”应该是“”(空白)或undefined.with唯一的ID。
ie 即
output = [{"from":2,"to":7,"id":0},{"from":3,"to":9,"id":1},{"from":2,"to":4,"id":6,"style":""}]
am able to get it as shown in below code, but i feel code can be optimized or there can be a better way to do it. 能够如下面的代码所示获得它,但是我认为代码可以进行优化或有更好的方法来实现。 Please help....Thanks.
请帮助...。谢谢。
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);
}
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.