© Russ Ferguson and Keith Cirkel 2017
Russ Ferguson and Keith CirkelJavaScript Recipes10.1007/978-1-4302-6107-0_8

8. Working with Arrays in Loops

Russ Ferguson and Keith Cirkel2
(1)
Ocean, New Jersey, USA
(2)
London, UK
 

How Do You Use a for Loop on an Array ?

Problem

You want to iterate through all the values of an array-like object where order is important.

Solution

A for loop lets you iterate through the values of an array in numeric order.

The Code

var alphaArray = ['a', 'b', 'c', 'e', 'd', 'e', 'f', 'g'];
var arrayLength = alphaArray.length;
for (let i = 0; i < arrayLength; i++){
     console.log(alphaArray[i]); //returns a,b,c,d,e,f,g
}
Listing 8-1.
Iterating Through an Array-Like Object with a For Loop

How It Works

For loops are often used when iterating through array-like objects. In Listing 8-1, we are using let to set a block level variable. This variable is available in the block and its sub-blocks. The variable is compared to the length of the array. If the current value, which starts at 0, is less than the length of the array (the number of elements in the array), then add 1 to the value. While the loop is happening, we log the value of the array. One of the important things to remember about using a for loop is you can control the range of elements you want to work with in order.

How Do You Use a for...in Loop with an Array?

Problem

You want to iterate through an array-like object using a for..in loop.

Solution

If you want to see all the enumerable properties of an array-like object, use a for..in loop.

The Code

var alphaArray = ['a', 'b', 'c', 'e', 'd', 'e', 'f', 'g'];
for (prop in alphaArray){
     console.log("alphaArray." + prop + " = " + alphaArray[prop]);  
}
Listing 8-2.
Looping Through an Array-Like Object with a for..in Loop

How It Works

For..in loops allow you to loop only over enumerable properties of array-like objects. This loop works in an arbitrary order. If order is important, use a for loop from the previous example. Built-in objects like arrays and objects have non-enumerable properties from Object.prototype and String.prototype.

How Do You Use a for...of Loop with an Array?

Problem

You want to loop over iterable objects that include Array, Map, Set, String, and TypedArray .

Solution

A for...of loop allows you to loop over collections. Over each iteration, the value of each property is assigned to a variable.

The Code

var alphaArray = ['a', 'b', 'c', 'e', 'd', 'e', 'f', 'g'];
for (let value of alphaArray) {
     console.log(value);  //returns a,b,c,d,e,f,g
}
Listing 8-3.
Using a for..of Loop on an Array

How It Works

The for..of loop allows you to work on each element of the array . Each iteration of the loop will assign the value of each property to the variable that you set in the loop. This variable is set using the let statement, which creates a block-level variable. It also can be set using the var statement. The second argument is the object that you are iterating over.

How Do You Loop Through an Array Using do...while?

Problem

You want to set conditions of a loop and iterate as long as the conditions are not met.

Solution

Using do...while loops allow you to loop based on a condition.

The Code

var planetExpressCrew = ['Fry', 'Bender', 'Amy', 'Lela' ];
var indexNum = 0;
do {
      console.log(planetExpressCrew[indexNum]);
      indexNum++;
}while(planetExpressCrew[indexNum] != 'Amy');  
Listing 8-4.
Do...while Lets You Loop Over an Object Based on Conditions

How It Works

The do...while loop will continue to execute until the condition evaluates a false value. This condition is evaluated after executing statements set up in the do block. Because of this, the statement is executed at least one time.

How Do You Use a while Loop on an Array?

Problem

You want to loop based on a condition, but have that condition evaluate to true.

Solution

The while loop is similar to a do..while but will stop if the condition results in a true value.

The Code

var planetExpressCrew = ['Fry', 'Bender', 'Amy', 'Lela' ];
var indexNum = 0;
while(indexNum < planetExpressCrew.length){
      console.log(planetExpressCrew[indexNum]);
      indexNum++;    
}
Listing 8-5.
The While Loop Will Iterate until the Condition Results in a True Statement

How It Works

Similar to the do...while in Listing 8-4, the while loop will continue until the condition results in a true value. The condition is evaluated before executing the statements.
If you want to first check a position before performing an action, the while loop would be appropriate. On the other hand, if you want the action to be performed at least once, a do/while loop would work.

How Do You Sort an Array?

Problem

You want to take the values of an array and convert them to a string.

Solution

To sort the contents of an array, you can use the sort method.

The Code

var planetExpressCrew = ['Fry', 'Bender', 'Amy', 'Lela' ];
console.log(planetExpressCrew.sort()); //returns  ["Amy", "Bender", "Fry", "Lela"];
Listing 8-6.
Using the sort() Method to Sort the Contents of an Array

How It Works

The Array object has a built-in sort method. This method will sort all the elements of the array in place. This type of sorting is not considered stable (See Wikipedia’s article on sorting algorithms at https://en.wikipedia.org/wiki/Sorting_algorithm#Stability ). This method can also accept a function to make custom comparisons. If it is not supplied to the method, it will sort elements based on the Unicode point value.

How Do You Sort a Multidimensional Array?

Problem

You have a multidimensional array that needs to be sorted.

Solution

The sort() method can be customized using a function.

The Code

var multiDArray = [[7,8], [3,4], [1,2], [5,6]];
multiDArray.sort(function(a,b){
     return a[0] - b[0];
});
console.log(multiDArray); //returns [[1,2], [3,4], [5,6], [7,8]];
Listing 8-7.
Sorting a Multidimensional Array

How It Works

Adding a function to the sort() method gives you the ability create a custom sort. Using this function, you can evaluate the elements and make comparisons. When making comparisons, the array is sorted based on the value returned from the function. In Listing 8-7, we compare the first two numbers in the subarray. If the value of a is less than b then return a. This will return an array in ascending order.

How Do You Run a Function for Each Element in Ascending Order?

Problem

You want to perform an operation on each element inside an array, in ascending order.

Solution

The forEach() method allows you to perform a callback function on each element of the array, in ascending order.

The Code

var myArray = [9, 2, 7, 6, 8, 5, 3];
myArray.forEach(function(element, index, array){
     console.log(element + ' element'); //returns 9, 2, 7, 6, 8, 5, 3
     console.log(element + ' index ');  //returns 0 ,1, 2, 3, 4, 5, 6
     console.log(element + ' array ');  //returns the entire array
});
Listing 8-8.
forEach Allows You to Perform a Function on Every Element of an Array, But Passes Undefined if There Is No Value

How It Works

The forEach() method will execute a function once for every method in ascending order. This function will not run on elements that have been deleted or are missing. This method works similar to other methods used on the array prototype. It will receive the element value, the index, and the array.

How Do You Test for a False Condition in an Array?

Problem

You need to check the elements for a value that does not meet the conditions you set up.

Solution

The every() method allows you to have a function that runs a test. The method stops when a false value is returned.

The Code

var myArray = [9, 2, 7, 6, 8, 5, 3];
myArray.every(function(element){
     console.log(element >= 1); //returns true
});
Listing 8-9.
Appending the Values of an Array to Another Array

How It Works

The every() method will run on every element similar to Listing 8-8. The important difference is that the callback function will evaluate the element and return true only if every element meets the conditions. Otherwise, it will stop evaluating and return false. This function is only called on indexes with a value.

How Do You Test for a True Condition in an Array?

Problem

You want to check the elements for a value that meets the conditions you set up.

Solution

The some() method will evaluate all elements until a true value has been returned.

The Code

var myArray = [9, 2, 7, 6, 8, 5, 3];
    myArray.some(function(element){
        console.log(element == 9); //returns true then false for all the other values
    });
Listing 8-10.
Reversing Elements in the Array Using the Reverse Method

How It Works

The some() method works very much like the example in Listing 8-9. The some() method returns true for the element that meets the condition. It will return false for everything else. Just like the every() method, it will not execute on indexes that do not contain a value or have been deleted.

How Do You Filter the Elements in an Array?

Problem

You need an array of only the elements that meet some certain criteria.

Solution

The filter() method will return a new array of only the elements that pass the test in the callback function.

The Code

var myArray = [9, 2, 7, 6, 8, 5, 3];
var elementsOver5 = myArray.filter(function(element){
     return element > 5;
});
console.log(elementsOver5); //returns [9, 7, 6, 8]
Listing 8-11.
Creating a New Array Using the filter() Method

How It Works

This method runs a callback function on every element. Similar to Listing 8-8, it will return a new array based on the current one using only the elements that either return true or coerces to true. Also like some of other examples, it will not run the callback function on indexes that do not have a value or were deleted from the array. Any elements that do not pass the test set up on the callback function are ignored and not included in the new array. The callback function receives the same parameters each time—the value of the element, the index number, and the array itself.

How Can You Reverse Each Word in a String in Place?

Problem

You want to reverse each word, but not change the order of the words.

Solution

Using map() on an array will allow you to run a callback function on every element of the array. This gives you the opportunity to perform work on the element and return a new array.

The Code

var phrase = 'It's the information age brother!';
var phraseArray = phrase.split(' ');
var reverseArray =  phraseArray.map(function(element){
         return element.split('').reverse().join('');
})
console.log(reverseArray); //returns ["s'tI", "eht", "noitamrofni", "ega", "!rehtorb"]
Listing 8-12.
Using map() to Reverse Each Element in the Array Like Object in Place

How It Works

Array.prototype.map() will run a callback function on every index in the array, including indexes whose value is undefined. It will not run the callback on indexes that are missing or were previously deleted. Like most methods on the array prototype, the callback can accept three values—the value of the element, its index, and the array that is being transversed. This method will return a new array based on the results returned from the callback function. If you are testing for a palindrome, you can compare the results to the original string using triple equals sign (===).

How Do You Combine the Elements in an Array into a Single Value?

Problem

You want to reduce the elements into a single value.

Solution

The reduce() method will allow you to run a callback function on each element. This gives you the opportunity to return a single value based on all the values in the array.

The Code

var numArray = [1,2,3,4,5,6];
var reducedValue = numArray.reduce(function(prev, current){
        return prev + current;
});
console.log(reducedValue); //returns 21
Listing 8-13.
The reduce() Method Can Return a Single Value Based on All the Values in an Array

How It Works

If you ever heard the term MapReduce , this is the reduce part of that programming model. This method, like others, takes parameters. In this case, the callback function will receive the previousValue, the currentValue, the currentIndex, and the array.
The first time the callback is executed an initialValue can be provided in the reduce method: reduce(function, initialValue).
If this is the case, the value used in the reduce call will be used as the previousValue. The currentValue will be the value of the first element in the array. If the initialValue is not provided, everything will shift over one position. The previousValue will be the first value in the array and the currentValue will be the second.
If the initialValue has been provided but the array is empty, the initialValue is returned without running the callback function. This is also true if the initialValue was not provided and the array has only one element.
If a initialValue has not been provided and the array is empty, the browser will return a TypeError.

What Is the Difference Between reduce and reduceRight?

Problem

How do you perform a reduce method starting from the right?

Solution

The reduceRight() method functions similar to reduce, but transverses the array from right to left.

The Code

var numArray = [1,2,3,4,5,6];
var reducedValue = numArray.reduceRight(function(prev, current){
        return prev + current;
});
console.log(reducedValue); //returns 21
Listing 8-14.
The shift() Method Will Remove the First Element in the Array

How It Works

The reduceRight() method works the same way as reduce does in Listing 8-13. The important difference is that you are traversing the array from right to left. ReduceRight uses the same rules as the reduce() method. This includes the callback function receiving previousValue, currentValue , the current index number, and the array being transversed.

How Do You Find Unique Values in an Array ?

Problem

You want to remove duplicate values from an array.

Solution

Use the filter and indexOf methods to create an array of unique values.

The Code

var  numArray = [2,2,3,6,7,7,7,7,8,9];
var uniqueArray = numArray.filter(function(element, index, arrayObj){
          return arrayObj.indexOf(element) == index;
});
console.log(uniqueArray); //returns [2, 3, 6, 7, 8, 9]
Listing 8-15.
Looping Through the Array Using the Filter Method and Creating a New Array of Unique Values

How It Works

Using the filter method, you can set the callback method and check the index of the element you are currently looking at. The indexOf method will return the first index number it can find using the element provided and will ignore the duplicate elements.

How Do You Keep Count of Values in an Array?

Problem

You want to know how many times a value is used in an array.

Solution

Use the forEach() method and save the count to another object.

The Code

var  numArray = [2,2,3,6,7,7,7,7,8,9];
var countObj = {};
var uniqueArray = numArray.forEach(function(element, index, arrayObj){
       if(countObj[element]){
               countObj[element] = countObj[element] + 1;      
                     }else{
                countObj[element] = 1;  
              }
      });
console.log(countObj); //returns Object {2: 2, 3: 1, 6: 1, 7: 4, 8: 1, 9: 1}
Listing 8-16.
Looping Through and Keeping Count of Each Element

How It Works

Using the forEach() method, we loop through every element in the array. Inside the callback function, we run an if statement to see if the property exists in the object we are calling countObj. If the property exists, then take the value and add 1; if not, then create the property on the object and give it a value of 1. Once the loop is finished the countObj will then have a count of every value in the array.

How Do You Get the Max or Min Value in an Array?

Problem

You need to find either the largest or smallest number in an array.

Solution

The Math object has a Max and Min method. Pass the array to either of these methods.

The Code

var  numArray = [2,2,3,6,7,7,7,7,8,9];
console.log(Math.max.apply(null, numArray)); //returns 9
console.log(Math.min.apply(null, numArray)); //returns 2
Listing 8-17.
Find the Largest Number in the Array or the Smallest

How It Works

The Math object contains a max or min method that will give you either the largest number in the array or the smallest. The call method allows an unlimited amount of parameters. This gives you the ability to pass the entire array to be processed.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.136.84