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

What is the reason behind one function triggering a re-render of a component while the other does not in Next.js?

I am currently working on a Next.js web application where one of the pages contains two functions that utilize useState() to add or remove emails from an array. const [invites, setInvites] = useState([]) // other code const lmao = () => { console.lo ...

What steps can I take to replicate a 'heap limit Allocation failed' error?

Context I encountered a challenging issue where my program displayed a FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory This occurred when the memory usage reached around 512 mb Scavenge (reduce) 507.8 (518.9) -> 507.2 ...

How to continuously animate images in HTML using Bootstrap

I want to showcase 7-8 client images in a continuous loop using a <marquee> tag. The issue is that there is a gap between the last and first images. Here is the HTML code I have: <marquee> <ul> <li><a href="#&q ...

Set YouTube Playlist to start from a random index when embedded

I've been trying to figure out how to set my embedded playlist to start with a random video. Here's what I attempted: <iframe src="https://www.youtube.com/embed/videoseries?list=PLPmj00V6sF0s0k3Homcg1jkP0mLjddPgJ&index=<?php print(ran ...

The WebSocket function is returning undefined even though it successfully fetches the user; however, the user is

I've been experimenting with a websocket to retrieve user information. When I establish the connection and send messages to receive the data, it returns undefined when I try to use that information elsewhere. However, if I run console.log within the ...

What is the best way to define properties for objects within views.py so that the updated object can be effectively passed to JavaScript code?

When loading an "endless scroll" feed via AJAX and pagination, I realized that before passing objects to the JS code, I need to add a property (or attribute) to every object indicating whether it was liked by the current user or not. However, my initial ...

iOS CORS ajax request is stuck at state 0 during processing

I am facing an issue with making a CORS login AJAX call from my iPhone using $.ajax. The request fails and reaches the fail callback, showing the jqXHR object state as: { readyState: 0, status: 0, statusText: "error" } Strangely, on my PC the request ...

Is the callback still triggered even after the off function is called?

Can someone help me with a scenario where despite calling the off on a reference, the callbacks are still being triggered repeatedly? var ref = new Firebase('https://example.firebaseio.com/123456'); for (var n = 0; n < 1024; ++n) { ref.pus ...

Restangular: Avoiding empty parameter being passed

In my AngularJS application using RestAngular, I have the following controller method: $scope.findFriend = function (name, type, limit) { return FriendSearch.getList({ name: name, type: type, limit: limit ...

Reduce the number of divs on a webpage while incorporating animated transitions

I've been attempting to incorporate an animation on the width property for my div .panels. I've tried using transition-property in CSS and also with .animate() in jQuery, but unfortunately, it doesn't seem to be working. I also noticed that ...

Having trouble capturing screenshots with PuppeteerJS?

I've encountered an issue while working with Puppeteer to capture screenshots from a provided URL. The code I have below doesn't seem to be functioning properly. It keeps showing the error message: [0] Error: Protocol error (Emulation.setDeviceM ...

The value for $routeParams.param appears to be undefined

I have set up a route and am attempting to send parameters to a controller: app.js .config(function($stateProvider, $urlRouterProvider) { $stateProvider .state('spot', { url: "/spot/:param", templateUrl: "templates/spot.html", ...

How can you create a smooth transition between two images in React Native?

I'm looking to create a cool effect with two images that gradually fade into each other. My initial approach involved layering one image over the other and adjusting its opacity using timing or animation functions, but I've been struggling to ge ...

Utilize MaterialUI Grid to define custom styles for the ::after pseudo-element

I came across a helpful article on Stack Overflow about Flex-box and how to align the last row to the grid. I'm interested in implementing it in my project: .grid::after { content: ""; flex: auto; } However, I'm not sure how to inc ...

JSON object name

Here are the specific file locations for loading each of the CSS and JS files. <link href="css/default.css" rel="stylesheet" /> <script src="js/main.js"></script> In XML, the filename is input as shown below ...

"Sending an array in a POST request using Javascript and processing it on the server

I am trying to use ajax to send an array. Let's say the array looks like this: var anotherOne = 'anotherOneData'; var documents = ['banana', 'apple', 'monkey']; I successfully sent both a normal value and an a ...

Storing a token in NodeJS using JavaScript

We currently have a mobile single-page application built using HTML/CSS/NodeJS. The functionality of this app requires numerous API calls, all of which require a bearer token for authorization purposes. This bearer token is simply a string value that we ge ...

Adjusting canvas/webgl dimensions to match screen width and height

Hey, I'm currently working on resizing my canvas/webgl to fit the window's height and width at 100%. It works initially, but when I resize the window from small to large, it doesn't scale/fit properly anymore and remains small. Any suggestio ...

How to populate an ExtJS 3.4 combobox with local JSON data in a few simple steps

I am utilizing ExtJS 3.4 and in need of populating a combobox with specific data obtained from a previous XMLHttpRequest, stored in a variable as follows: my_variable = "[{"cod_domini":"1","nom_domini":"Sant Esteve de Palautordera"},{"cod_domini":"2","no ...

When utilizing jQuery to add a <li> element, it suddenly vanishes

? http://jsfiddle.net/AGinther/Ysq4a/ I'm encountering an issue where, upon submitting input, a list item should be created with the content from the text field. Strangely, it briefly appears on my website but not on the fiddle, and no text is appen ...