'Round off number to the nearest Highest number from array besides last one

var counts = [2, 33, 61, 92, 125, 153, 184, 215, 245, 278, 306, 335, 365],
  goal = 35;

let min = Math.min(...counts.filter(num => num >= goal));

console.log(min)

This works but in case goal=400, I will get 365 back as it's the last number in the array



Solution 1:[1]

You could find the wanted value or take the value at last index.

const
    find = (array, value) => array.find((v, i, { length }) =>
        v >= value || i + 1 === length
    ),
    counts = [2, 33, 61, 92, 125, 153, 184, 215, 245, 278, 306, 335, 365];

console.log(find(counts, 35));
console.log(find(counts, 400));

A slightly different approach by taking the last item, if undefined.

const
    find = (array, value) => array.find(v => v >= value) ?? array.at(-1),
    counts = [2, 33, 61, 92, 125, 153, 184, 215, 245, 278, 306, 335, 365];

console.log(find(counts, 35));
console.log(find(counts, 400));

Solution 2:[2]

This will give you the smallest number above the goal, or the largest number in counts if there are no numbers above the goal

const counts = [2,33,61,92,125,153,184,215,245,278,306,335,365]
goal = 35;
const above_goal = counts.filter(num => num >= goal)
  
const min = above_goal.length === 0 ? Math.max(counts) : Math.min(above__goal)
  
console.log(min)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Cameron Ford