Функция Javascript для возврата значения между порогом объектов массива - PullRequest
0 голосов
/ 27 июня 2018

У меня есть следующий scores объект в JavaScript:

[
  {
    "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 голосов
/ 27 июня 2018

Если вы сначала сортируете массив 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);
0 голосов
/ 27 июня 2018

Даже если ваш массив 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);

Надеюсь, это поможет;)

0 голосов
/ 27 июня 2018

Вы, похоже, ищете первый элемент в массиве, чей порог ниже или равен прогрессу . Выражение

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

сделает это.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...