Eliminating duplicate elements from two arrays while awarding a higher score

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.

Answer №1

Develop a function that creates a link between URLs and elements of an array:

var urlMap = {};
for (var index = 0; index < array.length; index++) {
    urlMap[array[index].url] = array[index];
}

Utilize this map during the merging process:

for (index = 0; index < anotherArray.length; index++) {
    var currentUrl = anotherArray[index].url;
    if (urlMap[currentUrl]) {
        urlMap[currentUrl].count++;
    } else {
        array.push(anotherArray[index]);
    }
}

Custom Link

Answer №2

Opt for a single loop rather than a double loop when iterating over the second array. Verify if the URL of the current item exists in array1 for each iteration, and execute either the first or second scenario based on your preference. By doing so, you streamline the process by only interacting with each entry in array2 once.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When using NodeJS, it is important to add a delay after establishing the connection before invoking client.emit('message') to ensure that it is properly

My Node application utilizes socket.io. Below is an excerpt from my code: io.sockets.on('connection', socket => { setTimeout(function () { console.log('a client connected!') clients.forEach(s => s.emit(' ...

How can I maintain the consistent speed of the Javascript timer even when the .deck is clicked?

Currently, I'm working on creating a memory card game. In this game, the deck of cards is represented by the class .deck. Strangely enough, every time I click on a card, the timer starts to speed up instead of keeping a consistent pace. How can I tack ...

CSS styling can be used to generate a line break above and below a drop-down menu

While working on my CSS drop down menu, I noticed that it was generating unwanted line breaks before and after the dropdown. Below is the HTML code: <body> <!--nav class="navi"--> <div class="navi" id="navi"> <ul> <li& ...

Using PHP to dynamically change the title of a Bootstrap modal

I've been attempting to dynamically update the title of my modal using PHP. The title I wish to display is stored in a variable and is being reassigned based on user input. Below is my PHP code snippet: $studentName = $results['Studentname&apo ...

Randomly undefined custom jQuery function

Appreciate your assistance in advance. I am facing a peculiar scope issue on a page where multiple charts are rendered intermittently. I have created a set of jQuery functions to display different types of charts based on the provided options. Each funct ...

"Crafting a personalized legend with ChartJS: A step-by-step guide

Currently, I am working on creating a custom legend for my donut chart using the ChartJS library. While I have successfully created the donut chart with the default legend provided by ChartJS, I now require some modifications. Specifically, I would like t ...

Utilizing jQuery to add a class to an element when a different one is hovered above

I'm currently working on implementing effects on the edges of a webpage that will be triggered when a central div is hovered over. The main tool I'm using for this task is jQuery. Despite my efforts to diagnose the issue by using alerts in my Ja ...

Ways to track the number of distinct users visiting a webpage

I am trying to find a reliable method to track unique visitors on my webpage using JavaScript (ReactJS + NodeJS(Express). I want the system to identify each user when they load the page and add their data to the database if they are unique. So far, I have ...

Experiencing trouble with your ajax call and encountering an error?

After making an Ajax call to one of the pages on my server, I encountered an issue. Despite receiving a status code of 200 OK in red font color within Firebug, I did not receive the expected data. The source of this problem eludes me. The API pages I atte ...

The addEventListener function seems to encounter issues in IE11

There is a javascript function below that uploads the selected file and updates the grid. It works perfectly in Firefox, but there seems to be an issue with IE11. The "ESignature/Registration" function within the addEventListener does not seem to execute ...

The JavaScript function's if and else statements are being executed simultaneously

Upon loading the page, I am checking the value of a dropdown. Strangely, when I debug, it appears that the controller is executing both the if and else statements, which should not be happening. /* Here is my code: */ $(window).load(function() { ...

Organizing an array of items based on their attributes

I am currently facing a challenge with sorting an array of objects by their values. In order to achieve this, I am using the following code: function compare(a,b){return dict[a]-dict[b]} Object.keys(dict).sort(compare) This implementation works perfectl ...

Having trouble populating an OnsenUI list with AngularJS parse in Cordova

I have been working on retrieving a list of names from parse and adding them to an onsenui list. The parse query seems to be functioning correctly as I logged the results successfully, but for some reason, the list items are not appearing anywhere. Below ...

AngularJS JQ Widgets Chart Display Issue

Trying to incorporate a chart using JQ widget, the code snippet below shows my controller code. When making an ajax call to retrieve data from the server, the response is received but the chart displays the previous data of that variable as undefined. Hard ...

Ways to generate a unique random number from an Array without repetition using Javascript

Looking to retrieve a random number from an array of numbers known as cardNumbertemp. function shuffleCard(){ randomized = Math.floor(Math.random()*cardNumbertemp.length); for (var i = 0; i < cardNumbertemp.length; i++){ ...

Prevent duplicate form submissions when reloading using AJAX and Solve the header modification restriction issue

I've encountered an issue where the form is being resubmitted upon page refresh. While there are solutions available online for this problem, my situation is unique because I'm utilizing ajax to submit the form, resulting in only a section of the ...

Tips for setting a checkbox as checked based on a value using JQuery

My task is to set the checked status of my checkbox based on a data value. So far, I have been using the following method. $(document).ready(function(){ $('#add').click(function(){ $('#insert').val("Insert"); ...

The Redux store has been modified, yet the changes are not reflected in the

In my Posts.js component, I am mapping every object in the posts array. Within this function, I attempt to filter all notes that have the same post_id as the id of the current mapped post object and store them in a variable called filteredNotes. I then pas ...

The readFile function is not executing within a while loop

My goal is to send the updated contents of a text file over a socket connection using Express every time the file gets updated: console.log('Server running!'); var express = require('express'); var app = express(); var server = app.li ...

react component fails to rerender upon state change

I am struggling with a React functional component that includes a file input. Despite selecting a file, the text in the h1 tag does not change from choose file to test. The handleChange function is triggered successfully. A console.log statement confirm ...