Home > Back-end >  (JS) clean way to find smallest number greater than X in Set()
(JS) clean way to find smallest number greater than X in Set()

Time:11-20

I have a set of numbers and an init number.

const mySet = new Set{[1, 4, 5]}
const initVal = 2

I want to find the smallest number greater than the initVal in mySet.

I could do something like...

myArray = Array.from(mySet)
let smallestNumSoFar = Infinity
for (let num in myArray) {
    if (num > initVal && num < smallestNumSoFar) smallestNumSoFar = num; 
    }

But I was looking at this answer for python and it looks soo clean. Can anyone think of a nice one liner for javascript to do this? Something like Math.min of numbers>X in mySet

CodePudding user response:

Using the same efficiency of the Python example linked (O(n)), here's a simple one-liner.

const mySet = new Set([1, 4, 5]);
const initVal = 2

const min = Math.min(...[...mySet].filter((val) => val > initVal));

console.log(min);

You first need to convert the Set to an Array, then .filter it, and then use that with Math.min. Math.min expects multiple arguments, so the spread operator (...) is needed there. Similarly, to convert the Set to an Array (since Sets don't have a .filter method), it must be spread so that it's not an array with the 0th element being the set itself.

  • Related