I am dealing with two arrays that contain objects structured like this:
var array1 = {
1: {url:google.com, score:0},
2: {url:bing.com, score: 2},
3: {url:yahoo.com, score: 0},
4: {url:facebook.com, score: 5},
5: {url:dopgile.com, score: 1},
6: {url:ask.com, score: 10},
7: {url:duckduckgo.com, score: 10}
},
array2 = {
1: {url:google.com, score: 2},
2: {url:facebook.com, score: 3},
3: {url:twitter.com, score: 0},
4: {url:duckduckgo.com, score: 0},
5: {url:mamma.com, score: 4},
6: {url:myspace.com, score: 5}
};
Both Array 1 and Array 2 have unique elements individually. However, there are duplicates between the two arrays.
My goal is to merge Array 2 with Array 1 in a way that increments the score of the duplicate element in Array 1 by 1 when encountered.
For instance, if google.com is present in both arrays, during merging, the score of google.com in Array 1 should be increased from 0 to 1, without adding the first occurrence of google.com from Array 2 since it's a duplicate.
Similarly, elements 2, 3, 5, 6 will be merged without any score increase as they do not have duplicates in Array 1. However, duckduckgo being a duplicate will elevate its score in Array 1[7] to 11 without duplicating it.
The final merged array should look like this:
var array1 = {
1: {url:google.com, score:1},
2: {url:bing.com, score: 2},
3: {url:yahoo.com, score: 0},
4: {url:facebook.com, score: 5},
5: {url:dopgile.com, score: 1},
6: {url:ask.com, score: 10},
7: {url:duckduckgo.com, score: 11},
8: {url:facebook.com, score: 3},
9: {url:twitter.com, score: 0},
10: {url:mamma.com, score: 4},
11: {url:myspace.com, score: 5}
I've attempted to loop through the arrays using the following logic:
for(var j=0; j<10;j++) {
for(var k=0; k<10; k++) {
if(array1[k].url==array2[j].url){
array1[k].changeRankScore(array1[k].score+1);
}else{
// This is where I encounter issues with combining the arrays without duplications
}
}
}
Any assistance is appreciated.