JavaScript Arrays : finding largest

  • JavaScript, how do we return the biggest number on an array?
// sample code
var myArray = [4, 5, 6, 99, 68, 7, 24];
var biggestNum = 0;
for(var i=0; i< myArray.length; i++){
    if(myArray[i] > biggestNum){
        biggestNum = myArray[i];
     }
}
console.log(biggestNum);
// displays 99

A for loop is just a macro to activate a complex mechanism from the JavaScript library.  JavaScript uses the value of the temporary variable i on line 4 to read the value of each pocket on myArray, starting at position 0 with the first increment of i, (the score is i = 1, position = 0, and JavaScript reads value 4). As i gets further incremented, JavaScript reads the next array location. When i reaches a value equivalent to 7 which is the length of myArray, JavaScript stops its array reading and exits.

Meantime in the body of the loop something else is happening simultaneously. myArray is being compared to biggestNum at each position determined by i. It uses the value JavaScript is reading from the array, to compare with the value of biggestNum.

The third act comes when myArray at i is actually bigger than biggestNum. At this time, variable biggestNum assumes the higher value or keeps its value if it is higher. This happens for each location of the array until the count of i has reached the total length of myArray.

By the time JavaScript stops reading myArray, biggestNum has saved in its own pocket the highest of the values of the array ( assuming any of those values is actually bigger than the original value of biggestNum).

The rest is history, the value of biggestNum is outputted to the screen and voila, we’ve got liftoff!

Note: In my book JavaScript Objects Functions and Arrays Explained I introduce and explain JavaScript native methods such as max( ) and apply( ), a powerful combination that can substantially simplify the above script as see here.

  • JavaScript, how do we return the length of the longest string on an array?
var fruits = ["Apple", "Banana", "Orange", "Pomegranate", "Peach"];
var largest = 0;
for (var i = 0; i < fruits.length; i++) {
    if (fruits[i].length > largest) {
        largest = fruits[i].length;
    }
}
console.log(largest);

To return the length of the longest array item when comparing strings instead of numbers, we need to employ the string property .length, which tells JavaScript to counts the number of character of each item. On the last line in the loop body we assign the length of array fruits at position i to variable largest. console.log will display the number 11, which is the length of Pomegranate.

Could we had found the longest item if the item was a number, instead of a string? Yes we could, but we would have to convert each output to string like this:
Where we see fruits[i].length, we would have to change it to fruits[i].toString().length in all instants.

  • JavaScript, how do we return the longest string on an array?
var fruits = ["Apple", "Banana", "Orange", "Pomegranate", "Peach"];
var largest = 0;
var largestName = "";
for (var i = 0; i < fruits.length; i++) {
    if (fruits[i].length > largest) {
        largest = fruits[i].length;
        largestName = fruits[i];
    }
}
console.log(largestName);
// Displays Pomegranate

Now, if instead of returning the length, we want to return the longest string of the array, we need to add one more variable which is originally assigned to an empty string value. This new variable, largestName, is later assigned to the position of array fruits with the longest string value, based on the results found at the end of the loop traversing performed by i.

We can test what happens in the above script by plugging the script into our JavaScript Console. If you use Chrome, click on CTRL+SHIFT+j to open your console and paste the code. Before you do it, add the following line below the last fruits[i] on the body of the loop: console.log(largestName);

This will allow us to see how JavaScript picked Pomegranate as a result. You will see that Apple was picked first. Then Banana won over Apple. Finally Pomegranate took to lead and nothing else was larger than Pomegranate.

I will be writing more often now that my book on JavaScript has finally been published. Please be sure to review it.

If you love JavaScript like I do, you will enjoy reading it.
Use the free amazon “Kindle for PC” app to read it on your computer.

Advertisements

Author: tarau

technical writer, web technologies

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s