##### Series: Common Algorithms with Ruby and JavaScript

One of the most common algorithms we usually have to deal with is:

**Given an array of negative/positive integers, how to find the largest element in that array, without using max() for Ruby or Math.max() for JavaScript.**

**Ruby**

array = [34 , 16, 1, 66, 50, 42, -91, -145] def max(array) if array.length == 0 return nil end largest = array.first array.each do |number| if largest < number largest = number end end largest end puts "The largest number is #{max(array1)}" # -> The largest number is 66

**JavaScript**

var array = [34 , 16, 1, 66, 50, 42, -91, -145]; function max(array) { if (array.length === 0) { return } var largest = array[0]; for(var i = 0; i <= array.length; i += 1) { if (largest < array[i]) { largest = array[i]; } } return largest; } console.log("The largest number is " + max(array)); // -> The largest number is 66

Advertisements