Skip to content

Instantly share code, notes, and snippets.

@AlvisonHunterArnuero
Created April 14, 2024 05:02
Show Gist options
  • Save AlvisonHunterArnuero/d0107d38e960c40fecdf02fc83ad5e9c to your computer and use it in GitHub Desktop.
Save AlvisonHunterArnuero/d0107d38e960c40fecdf02fc83ad5e9c to your computer and use it in GitHub Desktop.
// 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