Javascript 数组中最近的值 我有一个总数,它是一个数字,在我的代码中会发生变化,我需要在一个数字数组中找到最接近的值,并在结果中返回索引,它应该是Mia Vobos。

Javascript 数组中最近的值 我有一个总数,它是一个数字,在我的代码中会发生变化,我需要在一个数字数组中找到最接近的值,并在结果中返回索引,它应该是Mia Vobos。,javascript,arrays,Javascript,Arrays,我试着匹配两个总和相等的人(总和与他们被问到的问题的总和有关),或者找到最接近的人 使用.map返回上面的结果,除了分数总和而不是单个分数 我希望输出结果是结果[2],即(Mia Vobos),因为她的三分最接近2分,但我得到元素。reduce不是一个函数。 我的人脉和他们的分数 变量peopleArray=[ { 姓名:“赫克托·巴尔德斯”, 照片:“, 分数:[ "5", "1", "4", "4", "5", "1", "2", "5", "4", "1" ] }, { 姓名:“泰勒·威

我试着匹配两个总和相等的人(总和与他们被问到的问题的总和有关),或者找到最接近的人

使用.map返回上面的结果,除了分数总和而不是单个分数 我希望输出结果是结果[2],即(Mia Vobos),因为她的三分最接近2分,但我得到元素。reduce不是一个函数。

我的人脉和他们的分数
变量peopleArray=[
{
姓名:“赫克托·巴尔德斯”,
照片:“,
分数:[
"5", "1",
"4", "4",
"5", "1",
"2", "5",
"4", "1"
]
}, {
姓名:“泰勒·威廉姆斯”,
照片:“,
分数:[
"5", "1",
"4", "4",
"5", "2",
"2", "5",
"4", "1"
]
}, {
姓名:“Mia Vobos”,
照片:“,
分数:[
"2", "1",
]
}
]
var总计=2
const result=peopleArray.map((值)=>{
返回{
name:value.name,
分数:value.scores.reduce((总数,分数)=>total+Number(分数),0)
}
});
控制台日志(结果);
for(设i=0;i
首先,element.reduce将不起作用,因为element不是数组。请参阅mdn文档以了解reduce:

其次,这里是一个开始/概述。请注意,这可能比您习惯的更高级,但我将其保留为开放状态,供您编辑并在其中添加我的评论。完全公开:如果是针对不使用typescript的类,您可能不想使用typescript

]


附加注释:您注意到函数getClosesMatch中的“:number”部分了吗?如果不使用typescript,可以删除该部分。如果你想成为一名前端/javascript工程师,我建议你学习typescript

这是一个家庭作业问题吗?是的,是Andrew。请说明到目前为止您尝试了什么以及为什么它不起作用。我在中做了。reduce不是一个函数我的代码在上面我丢失了我丢失了什么
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);