Created
April 14, 2024 05:02
-
-
Save AlvisonHunterArnuero/d0107d38e960c40fecdf02fc83ad5e9c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 6 - Closest to Zero | https://www.codewars.com/kata/59887207635904314100007b | |
function closestToZero(arr) { | |
arr.sort((a, b) => a - b); | |
let closest = arr[0]; | |
let distance = Math.abs(closest); | |
for (let num of arr) { | |
const currentDistance = Math.abs(num); | |
if (currentDistance <= distance) { | |
distance = currentDistance; | |
closest = num; | |
} | |
} | |
return closest; | |
} | |
console.log(closestToZero([2, 4, -1, -3])); // Output: -1 | |
console.log(closestToZero([5, 2, -2])); // Output: null | |
console.log(closestToZero([5, 2, 2])); // Output: 2 | |
console.log(closestToZero([13, 0, -6])); // Output: 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment