Найти ближайшее число в массиве, если расстояние одинаковое вывести левое
Данный код, не проходит этот тест
nearestValue([0,-2],-1) должно вывести -2, а выводит 0.
Тесты в этих массивах проходит.
nearestValue([4, 7, 10, 11, 12, 17], 100), 17);
nearestValue([5, 10, 8, 12, 89, 100], 7), 8);
nearestValue([-1, 2, 3], 0), -1);
Как можно реализовать, чтобы когда расстояние между значениями одинаковое выводило наименьшее?
function nearestValue(values: number[], search: number): number {
let countValue = values.length;
let nearest = values[0];
for (let i = 0; i <= countValue; i++) {
if (Math.abs(nearest - search) > Math.abs(values[i] - search)) {
nearest = values[i];
}
}
return nearest;
}
Ответы (1 шт):
Автор решения: Yaant
→ Ссылка
function nearestValue(arr, val) {
return arr.reduce((nearest, num) => Math.abs(num - val) >= Math.abs(nearest - val) && nearest < num? nearest : num);
}
console.log(nearestValue([0,-2],-1))
console.log(nearestValue([4, 7, 10, 11, 12, 17], 100));
console.log(nearestValue([5, 10, 8, 12, 89, 100], 7));
console.log(nearestValue([-1, 2, 3], 0));