Closest Value in Array

151
June 15, 2019, at 11:30 AM
I have a total which will be a number and will change throughout my code and I need to find the closest value in a array of numbers and return the index in the result which should be Mia Vobos.

Im trying to match two people whoses sum (sum relates to the values added up in the questions they were asked) equals each other or find someone who is closest.

Used .map to return whats up above except a sum of scores instead of individual ones I expected the output to be result[2] which is (Mia Vobos) because her score of three is closest to the total of 2, but i get 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

First, element.reduce will not work because element is not an array. See mdn docs for reduce: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

Secondly, here's a start/general outline. Be aware that this is probably more advanced than you are used to, but I left it open for you to edit and added my comments there. Full disclosure: You probably don't want to use typescript if it's for a class that doesn't use typescript.

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);

Additional comments: Did you notice the ': number' part in the function getClosestMatch? You can remove that part if you're not using typescript. I do recommend learning typescript if you want to be a frontend / javascript engineer though!

READ ALSO
What is the purpose of this array after the returned object?

What is the purpose of this array after the returned object?

Can someone describe the purpose of [thisprops

113
Chrome extension&#39;s content script makes the page load slow on some websites (possibly due to mutation observers)

Chrome extension's content script makes the page load slow on some websites (possibly due to mutation observers)

So I made a chrome extension to blur and unblur (when hovered) some profanity words that I'm storing in a json fileScript works fine for almost all sites I tested but makes the page loading slow for some sites like facebook and twitter (very poor perfomance...

116
d3: drawing a multi-line line graph from a 2d array of objects

d3: drawing a multi-line line graph from a 2d array of objects

I'm trying to draw a multi-line line graph in d3, and then update it on every tickThe problem I'm experiencing is that I end up with either an error a graph with zero data

288
Form onsubmit runs function but changes don&#39;t persist

Form onsubmit runs function but changes don't persist

I'm creating a little financial calculatorThis is a first time thing

90