Javascript函数返回数组对象阈值之间的值



我在 JavaScript 中有以下scores对象:

[
{
"id":37,
"title":"Over achieving",
"description":"Exceeding expectations",
"threshold":10,
},
{
"id":36,
"title":"Achieving",
"description":"Achieving expectations",
"threshold":6,
},
{
"id":35,
"title":"Under achieving",
"description":"Not achieving expectations",
"threshold":3,
}
]

我正在尝试弄清楚如何创建一个方法,该方法将根据分数阈值确定的值返回分数对象。

我已经尝试了以下内容,但仅当值等于分数阈值而不是分数阈值之间时,它才会返回分数。

scores.find(o => o.threshold <= progress && o.threshold >= progress)

所以场景是,一个人的进度value为 5,我希望该方法返回id为 35 的分数数组项,因为 5 介于 3 和 6 之间。同样,如果进度value为 7,那么我希望该方法返回id为 36 的分数数组项,因为 7 介于 6 和 10 之间。

我相信我离得不远了。

您似乎正在寻找数组中阈值低于或等于进度的第一项。表达式

scores.find(o => o.threshold <= progress)

会这样做。

如果先以相反的顺序对scores数组进行排序,则可以调整回调以找到threshold仅小于progress的第一个分数。

// doing it this way solely to keep it on a single line.
const scores = JSON.parse('[{"id":37,"title":"Over achieving","description":"Exceeding expectations","threshold":10},{"id":36,"title":"Achieving","description":"Achieving expectations","threshold":6},{"id":35,"title":"Under achieving","description":"Not achieving expectations","threshold":3}]');
const getScore = (progress) => scores.sort((a, b) => b.threshold - a.threshold).find(score => score.threshold <= progress);
const showScore = (progress) => {
const lowestThreshold = scores.sort((a, b) => a.threshold - b.threshold)[0];
const score = getScore(progress) || lowestThreshold;
console.log(`${progress} returns`, score.id);
};
const allValues = [...Array(15).keys()].map(showScore);

即使您的scores数组按阈值排序。

let progress = 5;
let scores = [{"id":37, "title":"Over achieving", "description":"Exceeding expectations", "threshold":10,}, {"id":36, "title":"Achieving", "description":"Achieving expectations", "threshold":6,}, {"id":35, "title":"Under achieving", "description":"Not achieving expectations", "threshold":3,}]
let item = scores.filter(o => (o.threshold <= progress)).reduce((acc, curr) =>  (curr.threshold >= acc.threshold)? curr: acc)
console.log(item);
console.log(item.id);

我希望这对;)有所帮助

相关内容

最新更新