数组中的最近值

时间:2019-06-15 00:32:54

标签: javascript arrays

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

我正在尝试匹配两个总和(总和与他们被问到的问题求和的值有关)彼此相等或找到最亲密的人。

使用.map返回除了分数总和而不是单个分数之外的其他内容  我期望输出是result [2],它是(Mia Vobos),因为她的得分3最接近总得分2,但是我得到element.reduce不是函数。

 

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


   

1 个答案:

答案 0 :(得分:1)

首先,element.reduce无效,因为element不是数组。有关缩减的信息,请参见mdn文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

第二,这是开始/一般概述。请注意,这可能比您以前使用的要先进,但是我将其保留供您编辑并在其中添加我的评论。全面披露:如果您的打字机不使用打字稿,那么您可能不想使用打字稿。

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

其他注释:您是否注意到getClosestMatch函数中的':数字'部分?如果您不使用打字稿,则可以删除该部分。我确实建议您学习打字稿,如果您想成为一名前端/ javascript工程师!