Comparing Two Arrays Of Objects For Duplicate Objects And Push It When It's Not A Duplicate In Javascript
This question might be too similar to this question I asked a few hours ago, but the issue I was struggling with is actually more complex than I initially thought. I was not aware
Solution 1:
A few things wrong with your code: you do need a nested loop, but not for why you're doing it here. If the cities in the target array aren't exactly the same as those in the source array, then some may never get pushed to the target array. Cities can also have the same name but be in different countries.
Assuming you can use ES5 features:
functionruthere(source, target) {
for (var i = 0; i < source.length; i++) {
var srcObj = source[i];
var tarObj = target.find(function (obj) {
return obj.city === srcObj.city && obj.country === srcObj.country;
});
if (!tarObj) {
target.push(srcObj);
break;
}
}
return target;
}
Edit: I'm mistaken, Array.prototype.find
is ES6, not ES5. Here's the ES3 version:
function ruthere(source, target) {
for (var i = 0; i < source.length; i++) {
var srcObj = source[i];
var tarObj;
for (var j = 0; j < target.length; j++) {
var obj = target[j];
if (srcObj.city === obj.city && srcObj.country === obj.country) {
tarObj = obj;
break;
}
}
if (!tarObj) {
target.push(srcObj);
break;
}
}
return target;
}
Solution 2:
Just use;
varfrom = [{
city: "seoul",
country: "korea"
}, {
city: "tokyo",
country: "japan"
}, {
city: "beijing",
country: "china"
}, {
city: "new york",
country: "usa"
}];
var to = [{
city: "seoul",
country: "korea"
}, {
city: "tokyo",
country: "japan"
}, {
city: "toronto",
country: "canada"
}];
functionruthere(source, target) {
for (var i = 0; i < source.length; i++) {
if (source[i].city !== target[i].city) {
target.push(source[i])
}
}
for (var i = 0; i < target.length; i++) {
$(".city").append((i + 1) + " " + target[i].city + "<br>")
}
}
ruthere(from, to)
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="city"></div>
Solution 3:
I would look into using underscore to help you achieve this: Underscore.js
This answer will probably be a very helpful answer: https://stackoverflow.com/a/28632359/5768113
Post a Comment for "Comparing Two Arrays Of Objects For Duplicate Objects And Push It When It's Not A Duplicate In Javascript"