Discover the best correlation among multiple arrays

I am currently developing a chat script that allows users to specify their interests. Upon connecting to the server, the client sends a JSON payload over WebSocket containing information such as ID, hash, auto message, and interests.

{"id": int, "hash": md5, "automessage": {...}, "interests": ["cars", "programming", "stackoverflow"]}

Each new connection is added to a waiting array, and when another user connects, the last object in the array is removed to create pairs. I now need to create a function that analyzes the interests of all objects in the waiting array and returns the one with the most common interests. For instance, if the waiting array includes:

[
    {"id": int,"hash": md5, "automessage": {...}, "interests": ["cats", "animals", "cars"]},
    {"id": int,"hash": md5, "automessage": {...}, "interests": ["programming", "ssh", "stackoverflow"]},
    {"id": int,"hash": md5, "automessage": {...}, "interests": ["climbing", "football", "coffee"]}
]

Upon receiving a message, the system will search through the array and return the object with the most similar interests. In this example, it would be

{"id": int,"hash": md5, "automessage": {...}, "interests": ["programming", "ssh", "stackoverflow"]}
.

If no matching interests are found, the user will be added back to the waiting list.

I'm facing some challenges with this task, so any assistance would be greatly appreciated.


I'm not sure why this question received downvotes. Any feedback would be helpful.

Answer №1

To tackle the task of finding the closest element, you can use the following code snippet:

function intersection(arr1, arr2) {
    return arr1.filter(function(element) { 
        return arr2.indexOf(element) >= 0;
    });
}

function closestElement(inputArray, arrayOfArrays) {
    return arrayOfArrays.map(function(array) {
        return [intersection(inputArray, array).length, array];
    }).sort(function(a, b) {
        return b[0] - a[0];
    })[0][1];
}

For example:

myInterests = ["cars", "programming", "stackoverflow"];

interestsArray = [
    ["cats", "animals", "cars"],
    ["programming", "ssh", "stackoverflow"],
    ["climbing", "football", "coffee"]
];

console.log(closestElement(myInterests, interestsArray));
> programming, ssh, stackoverflow

Answer №2

Check out the DEMO

If you're looking to identify the best candidate from a waiting list, this snippet might help. If no suitable candidate is found, it can be added to the list.

 var incomingData = {
    "id": 'int',
        "hash": 'md5',
        "automessage": {},
        "interests": ["cars", "programming", "stackoverflow"],
};

var waitingCandidates = [{
    "id": 'int',
        "hash": 'md5',
        "automessage": {},
        "interests": ["cats", "animals", "cars"]
}, {
    "id": 'int',
        "hash": 'md5',
        "automessage": {},
        "interests": ["programming", "ssh", "stackoverflow"]
}, {
    "id": 'int',
        "hash": 'md5',
        "automessage": {},
        "interests": ["climbing", "football", "coffee"]
}];

// var exists = (myNumbers.indexOf(bar) > -1); //true

var highestMatchCount = 0, matchingIndex; // will contain the count & index of largest match
for (var k = 0; k < waitingCandidates.length; k++) { 
    var currentCandidate = waitingCandidates[k];
    var currentMatchCount = 0; 
    var incomingInterests = incomingData.interests; 
    for (var m = 0; m < incomingInterests.length; m++) {

        if(currentCandidate.interests.indexOf(incomingInterests[m]) > -1) { 
           currentMatchCount++; 
        }
        if(currentMatchCount > highestMatchCount) { 
            highestMatchCount = currentMatchCount;
            matchingIndex = k; 
        }
    }
    currentMatchCount = 0;
}

if(matchingIndex >= 0) {
console.log(waitingCandidates[matchingIndex]); 
} else {
    // add to waiting list
    waitingCandidates.push(incomingData);
}

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

"Step-by-step guide on adding and deleting a div element with a double click

$(".sd").dblclick(function() { $(this).parent().remove(); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table width="750" border="0" cellpadding="0" cellspacing="0"> <tr> <t ...

Differentiate among comparable values through placement regex

I'm currently tackling a challenge involving regex as I work on breaking down shorthand CSS code for the font property. Here is my progress thus far: var style = decl.val.match(/\s*(?:\s*(normal|italic|oblique)){1}/i); style = style ? style ...

How to Implement Autoplay Feature in YouTube Videos with React

I'm having trouble getting my video to autoplay using react. Adding autoplay=1 as a parameter isn't working. Any ideas? Below is the code I am using. <div className="video mt-5" style={{ position: "relative", paddingBot ...

Using jQuery validation to verify that a minimum of one radio button holds a true value

I have a form with two questions. The first question asks if the product value exceeds a certain fixed amount, and the second question asks if the product value is below that fixed amount. Upon submitting the form, validation should ensure that at least on ...

What is the best way to efficiently transmit Objects through AJAX utilizing bodyParser in node.js express?

Currently attempting to execute: $.ajax({ type:"POST", url:"/psychos", data:JSON.stringify(this.psycho) }) Upon reaching the server, I encounter the following: app.post("/psychos", function(request, respon ...

Navigating the way: Directing all TypeScript transpiled files to the build folder

I am currently working on a project using Angular2/Typescript, and I have the tsconfig.js file below: { "compilerOptions": { "module": "commonjs", "moduleResolution": "node", "target": "es5", "sourceMap": true, ...

What could be the reason for the child element not occupying the full height of its parent container?

* { padding: 0; margin: 0; box-sizing: border-box; } body { margin: 50px; } .navbar { display: flex; align-items: center; justify-content: center; color: darkgreen; font-family: 'Vollkorn', serif; font-size: 1.2rem; font-w ...

Retrieving a map using latitude and longitude coordinates saved in a database

I have a webpage with an embedded Google Map and a dropdown list of cities. The latitude and longitude values for each city are stored in a database. When a user selects a city from the dropdown list and clicks submit, I want the map to load with the corre ...

Combining the devexpress dxDataGrid with Angular's $scope for seamless web development

I'm encountering difficulties with binding $scope in angular and dxDataGrid. Utilizing the devexpress library dx.all.js, which enhances the dxDataGrid with various features, I have a div for dx-data-grid and attempting to transfer the selected row da ...

The styling of the CSS is tailored to various breakpoints

source: Display helpers How can I dynamically change CSS styles based on the current breakpoint size? For example, can I set different sizes, positions, and colors for elements when the window is on xs compared to md or other breakpoints? ...

Issue with event.preventDefault() in Jquery not functioning as expected

My goal is to have the menu display and hide list items on click, with them being hidden by default. However, the issue I am facing is that the menu is generated in the admin section, so it automatically assigns a URL to each item. If I set the URL field o ...

What is the most efficient way to use the $slice operator on a highly nested array in mongoose

I am currently working on slicing a deeply nested array. To illustrate, consider the following structure. I aim to slice this array for pagination purposes. {messages: [{ message: { members: [ {example: object, blah: blah}, {example2: object2, blah2: blah ...

Streamlining programming by utilizing localStorage

Is there a more efficient way to streamline this process without hard-coding the entire structure? While attempting to store user inputs into localStorage with a for loop in my JavaScript, I encountered an error message: CreateEvent.js:72 Uncaught TypeErr ...

producing base64 encoding that results in a blank image

I have some code that is supposed to get an image from a video using canvas. However, when I save this base64 code into an image, I end up with a black image. What could be causing this issue? Here is my JavaScript code: var input = document.getElementBy ...

Efficiently organizing reducers into separate files in ReactJS and merging them together

My App is a simple counter app where buttons are images with their own counters. https://i.stack.imgur.com/qkjoi.png In my App.js file, I imported the reducer for the counters using the following code: import reducer from './reducers/reducerCounter&a ...

How to set default props in Vue Select component?

I have been utilizing the vue-multiselect plugin from this website: Given that I plan to use it frequently, I am interested in establishing some default props. For instance, my aim is to have the selectLabel prop set as an empty string and possibly con ...

How can I access a method from another JavaScript file (service) in React JS's App.js to make API requests?

Just starting out with React js and trying to utilize REST API data. I've created a separate file named /shared/job-service.js for this purpose. My goal is to call a method from job-service.js in App.js and display the results on the UI. However, I&ap ...

Ways to conceal all components except for specific ones within a container using JQuery

My HTML structure is as follows: <div class="fieldset-wrapper"> <div data-index="one">...</div> <div data-index="two">...</div> <div data-index="three">...</div> < ...

What is the process for printing with JQuery?

I have nested divs with dynamically generated images in my HTML code. My problem is that when I click the print button, I want the corresponding image to be printed. <div id="outputTemp" style="display:none"> <div id="rightoutputimgae"> <di ...

Is it feasible to maintain a variable as a reference across views while utilizing ng-view?

I am facing a unique challenge: I have a webpage with two tabs that need to utilize ng-view from AngularJS. The twist is that both tabs must share the same variable, similar to referencing a variable in C# using the "ref" keyword. If you want to see an ex ...