Calculate maximum and minimum in array (Helper)

function polar(arr) { var maxVal, minVal; if (Array.isArray(arr) && arr.length) { maxVal = arr[0]; minVal = arr[0]; for (var i=1; i < arr.length; i++) { if (arr[i] > maxVal) { maxVal = arr[i]; } else { if (arr[i] < minVal) minVal = arr[i]; } // End of greater or less than } // End of array iteration return { max: maxVal, min: minVal }; } else { console.log('No array or empty array passed to polar().'); return arr; // Throws back the item passed } // End of: If it's an array and it isn't empty, then... } // End of Polar Function // CASE OF USE //----------------------------------------------- var numbers = [4, 2, 7, 10, 9, 1, 8, 5]; console.log(polar(numbers).max); // Outputs -> 10 console.log(polar(numbers).min); // Outputs -> 1 console.log(polar("5 4 2").min); // Outputs -> "No array or empty array passed to polar()." console.log(polar([]).min); // Outputs -> "No array or empty array passed to polar()."
Helper function to calculate the maximum and minimum integer number inside an array ─ This snippet is a piece of a JavaScript library I'm working on, you can see it here: https://github.com/luishendrix92/WindowbirdJS

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.