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