Finding the Nearest Value in an Array

My code involves a changing total number that I need to match with the closest value in an array of numbers, returning the index of the matching person, which should be Mia Vobos.

I am attempting to find two people whose scores add up to the same total or find the person whose score is closest to the total.

Using .map to calculate the total scores instead of individual ones, the expected output is result[2] indicating Mia Vobos, as her score of three is the closest to the total of 2. However, I encountered an error stating that element.reduce is not a function.

 

My array of people and their scores
var peopleArray = [
    {
        name: "Hector Valdes",
        photo: "",
        scores: [
            "5", "1",
            "4", "4",
            "5", "1",
            "2", "5",
            "4", "1"
        ]
    }, {
        name: "Tyler Williams",
        photo: "",
        scores: [
            "5", "1",
            "4", "4",
            "5", "2",
            "2", "5",
            "4", "1"
        ]
    }, {
        name: "Mia Vobos",
        photo: "",
        scores: [
            "2", "1",
            
        ]
    }
]

 
var total = 2
const result = peopleArray.map((value) => {
        return {
            name: value.name,
            score: value.scores.reduce((total, score) => total + Number(score), 0)
        }

    });
    console.log(result);

for (let i = 0; i < result.length; i++) {
        const element = result[i].score;
        if (total == result[i].score) {
            console.log(result[i])
        } else {

            var closest = element.reduce(function(prev, curr) {
              return (Math.abs(curr - total) < Math.abs(prev - total) ? curr : total);
            });
        }
    }

console.log(closest);


   

Answer №1

Initially, it's important to note that element.reduce won't be effective as element is not an array. Refer to the MDN documentation on reduce for more information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

Moreover, here is a basic/general structure to get you started. Please be aware that this may be more complex than what you're accustomed to, and feel free to make adjustments or add comments. It's worth mentioning that if your class doesn't involve typescript, you might not want to use it.

https://codepen.io/anon/pen/MMKEvg?editors=1012

const peopleArray = [
{
    name: "Hector Valdes",
    photo: "",
    scores: [
        "5", "1",
        "4", "4",
        "5", "1",
        "2", "5",
        "4", "1"
    ]
}, {
    name: "Tyler Williams",
    photo: "",
    scores: [
        "5", "1",
        "4", "4",
        "5", "2",
        "2", "5",
        "4", "1"
    ]
}, {
    name: "Mia Vobos",
    photo: "",
    scores: [
        "2", "1",

    ]
}

]

function getClosestMatch(total:number) {

 // First add the totals to each person
     peopleArray = peopleArray.map((person) => {
       person = {
         ...person,// This is called destructuring (look it up)
          total: // Insert your code here, and make sure to do parseInt(stringNumberValue, 10)
       }
       return person;
     })

    // Then just get the closest match
    var closestMatchingPerson = peopleArray.reduce(function(prev, curr) {
        return // Calculate the difference here, and return either previous or current
    });

  return closestMatchingPerson;

}

getClosestMatch(31);

Extra notes: Have you observed the ': number' portion in the function getClosestMatch? You can delete that part if typescript is not being used. However, if you aspire to become a frontend/javascript engineer, it's advisable to learn typescript!

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

Utilizing Ajax to dynamically load files within the Django framework

My current project involves working with Django, specifically a feature that requires loading a file and displaying its content in a textarea. Instead of storing the file on the server side or in a database, I am exploring the use of AJAX to send the file ...

Uploading Images Dynamically with AJAX

Can someone assist me with a multiple upload form that utilizes AJAX to upload and display an image without the need for a submit button? My issue arises when dealing with repeating forms within table rows, causing only the first form to function properly. ...

Transferring attributes from grandchildren to their ancestor

My React.js application structure looks like this: <App /> <BreadcrumbList> <BreadcrumbItem /> <BreadcrumbList/> <App /> The issue I am facing is that when I click on <BreadcrumbItem />, I want to be able to ch ...

Ways to delay the inner function's output?

Need help with making a function return only after its inner function is called. See below for the code snippet - function x() { function y() { // Inner function logic } return result; // This should be returned only after function y is ca ...

Built-in Promises within MongoDB

Is there a way to determine which methods in mongoDb have an inbuilt promise? For example, "updateOne() , findOne()" have inbuilt promises that we can access using ".then", but many other mongoDB methods lack this feature. How can we identify which methods ...

AngularJS is throwing an error because the term "grunt" has not

Today is the day I embark on my journey with Grunt for testing my JavaScript code. All the necessary grunt modules have been successfully installed and are documented in a json file called package.json. { "name": "LarissaCity", "private": true, ...

Tips for displaying animations only the first time using HTML and CSS:

Upon the initial visit to my website, a captivating animation introduces itself with the words "Hello. I'm Bob" as it gracefully fades into view. Navigating through the menu bar allows users to explore different sections of the site. However, there ...

Which is quicker: accessing the initial element of an array or the 4000th?

Are there speed variations when reading from the initial element of an array compared to the 4000th? This applies to any other element in the array as well. I'm primarily inquiring about c++, but insights regarding any programming language are welcom ...

What could be the reason for my function failing to return true?

I have a function that can check if a script is loaded: function checkURLExistence(url){ $.ajax({ url: url, success: function(data){ //alert(url + ' exists'); console.log(url + ' exists'); return ...

Create an array mapping of locations and convert each location to its corresponding language

With Next.js, I have successfully retrieved the current locale and all available locales for a language selection menu: const {currentLocale, availableLocales} = useContext(LangContext); // currentLocale = "en-US" // availableLocales = ["en- ...

Stop the parent script from executing

I recently encountered an issue with my DotNetNuke website. Embedded within the DNN code is a script that triggers a function called WebForm_OnSubmit(). However, I noticed that this function is also being triggered when I try to perform a search on a speci ...

comparing values in an array with jquery

I am attempting to retrieve the phone number and mobile number from an array using jquery. jQuery: var data = $('#PhoneLabel').text(); var array = data.split(', '); $.grep(array, function (item, index) { if (item.charAt(0) === &ap ...

View a specific selected newsAPI article on its own dedicated page

I have been working on a news website and successfully displayed all the articles on a single page using the news API in nodeJs. Everything is functioning well, but now I want to show the clicked article on a separate page. Although I managed to route it t ...

Incorporating CSS into React.js applications

I am currently working on a project using MERN.io. In my project, I am utilizing the React.js component Dropdown. However, the Dropdown component does not come with its own style and CSS, resulting in no styling at all. ... import Dropdown from 'rea ...

Ensure that Ajax requests are successfully executed when a user navigates away from the page

I have developed an HTML/JavaScript application that requires an AJAX request to be made when the user refreshes or closes the page in order to close the application gracefully. To achieve this, I am using the pageunload event. I have implemented the func ...

Encountered an error in React JS and Axios when attempting to select a form: "Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'."

I'm encountering an issue while attempting to send FormData using Axios within a React JS application. The form should include both text inputs and multiple file uploads. However, when I tried to select the form with querySelector, it doesn't app ...

sending a file using ajax and handling it with php

Curious if there's a way to upload a binary file through ajax and php, without having to refresh the entire page like with a traditional html form. I've been able to gather input from radio buttons and text boxes using forms and javascript, but w ...

The JSON response is being overridden by a catch-all URL and ends up being displayed as a 404 error page

I'm dealing with a React/Express setup that looks something like this (simplified for clarity): const path = require('path') const express = require('express') const CLIENT_BUILD_PATH = path.join(__dirname, '../build') ...

Uploading video files using XMLHttpRequest encountered an error on a particular Android device

One of our testers encountered an issue where they failed to upload a video file (.mp4) on a specific Android mobile phone. Interestingly, the same file uploaded successfully on an iPhone and another Android device. To investigate further, I attempted to ...

What is the best way to identify errors in an express listen callback function?

My current code is set up to verify if there was an error while initiating Express: express() .listen(port, (err: Error) => { if (err) { console.error(err); return; } console.log(`Express started`); ...