Locate all the small values within a given array

I am working on an application that involves gathering input from users for ten questions using select drop down boxes. The values range from 1 to 5 for each question. Upon clicking the submit button, I collect all the input values and store them in an object which is then sent via a $.post request route. On the server side, I process the data by comparing it with an array of 'friends' scores and calculating the differences. My challenge lies in determining how to identify and return multiple 'friends' who have the same lowest score difference.

frontside.js

$('#submit').on('click', function(){

            var newProfile = {
                name: $('#name').val().trim(),
                photo: $('#link').val().trim(),
                scores: []
            };

            for(var x = 0; x < questions.length; x++){
                var num = parseInt($('select[name = "q' + (x+1) + '"]').val());
                newProfile.scores.push(num);
            }

            alert("Adding profile");

            var currentURL = window.location.origin;

            $.post(currentURL + "/api/friends", newProfile).done(function(data){
                console.log('data', data);
            });

server.js

var friends = require('./../data/friends.js');

app.post('/api/friends', function(req, res){
        console.log('hi')
        var person = req.body;
        var diff = [];
        var low = 0;
        var match = [];


        for(var x = 0; x < friends.candidates.length; x++){

            for(var i = 0; i < friends.candidates[x].scores.length; i++){

                var result = person.scores[i] - friends.candidates[x].scores[i];

                 if(result < 0){
                    var positive = result * (-1);
                    diff.push(positive);
                 }
                 else
                    diff.push(result);
            }

            //adding up the differences from each score
            var added = diff.reduce(function(a, b){
                return a + b;
            }, 0);

            //This is where I need to figure out how to store multiple lowest numbers of same value.
            if(x === 0){
                low = added;
                match.push(friends.candidates[x]);
            }
            else if(low > added){
                low = added;
                match[0] = friends.candidates[x];
            }

            finalNum.push(added);
            diff = []; 
        }

        friends.candidates.push(person);
        res.send(match);

    });

friends.js

exports.candidates = [
    {

        scores:[5,1,4,4,5,1,2,5,4,1]
    },
    {

        scores:[4,2,5,1,3,2,2,1,3,2]
    },
    {

        scores:[5,2,2,2,4,1,3,2,5,5]
    },
    {

        scores:[3,3,4,2,2,1,3,2,2,3]
    },
    {

        scores:[4,3,4,1,5,2,5,3,1,4]
    },
    {

        scores:[4,4,2,3,2,2,3,2,4,5]
    },
    {

        scores:[2,3,3,3,3,3,3,3,3,3]
    },
    {

        scores:[5,2,1,1,5,2,1,1,4,4]
    }];

Answer №1

Give this a try.

// keep track of the smallest difference
var minDifference = Number.MAX_SAFE_INTEGER;
// list of friends with the smallest difference
var closestFriends = [];
for(var index = 0; index < friendsPool.length; index++){
            // variable to sum up the differences
            var totalScoreDiff = 0;
            for(var i = 0; i < friendsPool[index].scores.length; i++){

                var diffCalculation = user.scores[i] - friendsPool[index].scores[i];

                 if(diffCalculation < 0){
                    diffCalculation = diffCalculation * (-1);
                 }
                 totalScoreDiff += diffCalculation;
            }

            if(totalScoreDiff < minDifference) {
                minDifference = totalScoreDiff ;
                //clear previous array
                closestFriends.length = 0;
                //add the current friend data
                closestFriends.push(friendsPool[index]);
            }
            else if(totalScoreDiff == minDifference) {
                // store friend data 
                closestFriends.push(friendsPool[index]);
            }
}

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

How to automatically center Google Maps and update marker on responsive resize

Trying to figure out how to maintain the center of Google Maps while resizing responsively has been a challenge. I've successfully centered the map, but I'm struggling to include my marker in the JavaScript code so that it stays centered as well ...

Including a cancel button to close the open window

var messagebox = Ext.widget("messagebox", { target: grid, progressMessage: "Loading" }); The message box displayed above indicates the loading progress bar that appears when the download button is clicked. I am looking to incorporate a cancel button i ...

Looking for a way to assign customized thumbnails to images in react-responsive-carousel and react-image-magnifiers?

I am currently working on a product viewer using react-responsive-carousel and react-image-magnifiers. Following an example from this GitHub repository, I encountered an issue with mapping custom thumbnails correctly. Although hard-coding the array works f ...

Refine your search by focusing on select characteristics of an item

Is there a way to filter tasks in a table using only specific attributes provided in the table? Currently, when I enter a search term in the search bar, tasks are displayed even if they have attributes that match the input but are not displayed in the na ...

Issue with Angular2 Router not recognizing route for homepage

I recently incorporated the Angular2 Webpack Starter into my Angular2 app, which has been working great. However, after adding a fallback route to my app.routes.ts file and including its module (NotFoundModule) in app.module.ts, I encountered an issue wher ...

Unable to open modal using a button in PHP

<?php $result = mysqli_query($con, $sql); while ($row = mysqli_fetch_array($result)) { echo '<tr><td>'; echo '<h5 style="margin-left:6px; color:black;">' . $row['id'] . '</h5> ...

Utilizing Hubot for efficiently parsing JIRA webhooks

In my current project, I am working on decoding a JIRA webhook using a Hubot script. Right now, I have a basic Hubot script that simply displays the posted body: module.exports = (robot) -> robot.router.post '/jirawebhooks/foo-tickets', (r ...

Identify and track colored dots within an image using tracking.js

I'm working on creating a program that can tally the number of dots on dominoes in an image, such as the one shown here: https://i.sstatic.net/NKHXl.jpg My goal is to develop this functionality using JavaScript. I've attempted to learn how to u ...

Creating a Halo (external outline) for a circular sector in THREE.JS

I'm working on adding a halo (external black outline) to certain shapes in three.js. While I was able to achieve this easily with rectangles and circles, I am facing challenges with circular sectors (not full circles). Here is my current attempt: It ...

What are the potential disadvantages of relocating the login logic from the 'signIn()' function in NextAuth.js?

My experience with NextAuth.js for the first time has led me to realize that signing in using the Credentials provider can be a bit tricky when it comes to error handling. It seems like the default implementation should resemble something along these lines ...

What are the best practices for maintaining consistency with session variables between Express and Socket.io in a single-page application?

I am currently dealing with an issue in my single page app where the middleware is attaching my express session to my socket before a user is logged in. Refreshing the site after logging in works, but I need a more efficient solution. Is there a way to con ...

Utilizing an external JavaScript file for developing applications on Facebook

I am looking to incorporate external JavaScript into my Facebook application development. Specifically, I am hoping to utilize the Ajax tab feature in my application. ...

Is there any other factor aside from the lack of a CSRF token in an AJAX request with Django that could lead to a 403 error?

The primary reason behind the django + ajax 403 error is usually the absence of a csrf token. However, in my scenario, the csrf token is present and a similar ajax function is working fine. I will also provide the backend view function that handles the res ...

The NodeJs and Express API, integrated with Ejs files, encounters a crash when attempting to retrieve data from the database on the second attempt

I've been assigned the task of developing an API that retrieves data from a database and presents it on the frontend. This is my first time working with APIs, and I've encountered some challenges along the way. The database I'm using is call ...

The execution of events.js failed at line 136, causing an unhandled 'error' event to be thrown

Why do I keep getting events.js:136 throw er; Unhandled 'error' event and how can I fix it? I have already tried reinstalling both nodejs and mongodb, but the error persists. package.json { "name": "bookstore", "version": "1.0.0", "description" ...

Display a hyperlink in an iframe on the main page from a different domain using JavaScript

I'm currently using Angular with Wirecard as my payment provider. When I need to add a payment, I open an iframe that directs the user to the Wirecard site to accept the payment. Once the user clicks accept, I provide a link back to my site from Wirec ...

Encountering unusual JSON formatting when using the HTTP GET method with Node.js/Express

Currently, I am facing an issue with parsing data from keepa API as it returns a JSON format that standard JSON parsers cannot handle. Surprisingly, when I make the same request in Postman, the response is a readable JSON. Can someone help me figure out ...

The $http.get() function in Angular fails to function properly when used in Phonegap DevApp

Trying to retrieve a JSON file in my Phonegap App using angulars $http is causing some issues for me. I have set up this service: cApp.factory('language', function ($http) { return { getLanguageData: function () { return ...

How can I make an Object3D in Three.js look towards the near side of the view frustum instead of a point or rendering like a sprite

Just beginning my journey into 3D programming here. Experimenting with three.js and Spine to bring 2D characters to life in a 3D environment. Specifically, looking to render Mesh as Sprite - meaning objects maintain a parallel view rather than always fac ...

Why is the middleware content being executed four times when a single request is made from the browser?

Can you figure out why console.log('First Log') is executed 4 times in a single request? //app.js const express = require('express'); var app = express(); app.use((req, res, next) => { console.log('First Log'); // the i ...