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

时间:2018-06-27 15:07:11

标签: javascript ecmascript-6

我在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之间。

我确定我离你不远。

3 个答案:

答案 0 :(得分:1)

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

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

会这样做。

答案 1 :(得分:0)

如果您首先以相反的顺序对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);

答案 2 :(得分:0)

即使您的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);

我希望这会有所帮助;)