Get the closest number out of an array
Let's find the closest number to a target in an array using good old Array.prototype.reduce()
:
The architect of success here is comparing the Math.abs
differences to the target - the smallest divergence gives us our closest number.
Checkmate edge cases: "Hold my coffee"
Before being an array ninja, let's ready our defenses against potential Gotchas.
Edge control: on point
Before embarking on the closest number quest, we ensure our arsenal (arr
and target
) are in form:
- The
arr
is not hanging out in the void (a.k.a empty). arr
soldiers and ourtarget
are true numbers, not just masquerading.- Our
target
doesn't go rogue, staying within bounds (-1000 to 1000).
Our code might look like this:
Sorted arrays: Order in a chaotic world
In case of a massive arr
, a binary search zips through our data with O(log N) performance boost. Yes, you heard it -maths guys call it "logarithmic time".
- First, we align the array elements. Chaos has no place here.
- We implement an efficient binary search to station the closest index.
Currying: Flavour of functional programming
Nothing like a dash of currying to spruce up our function, allowing its reuse for different scenarios.
Special scenarios: Above and beyond
Now that we conquered the basics, let's scoot over to complex terrains.
Array includes the target: What a hit!
In rare occurrences, our arr
might be holding the target captive. We simply return it:
This also doubles as our early exit stratagem, improving performance where an exact match is spotted.
Currying adjustment: Change is the only constant
Finally, curryNearest
helps us shuffle the target
values for distinct scenarios; through placeholders:
Libraries for currying: A pinch of lodash
Show off your prowess by leveraging libraries like Lodash to ship out curry
function:
Was this article helpful?