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

7. Working with Arrays

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

What Is an Array?

Problem

You want to hold on to information in sequence without creating multiple variables.

Solution

Use an array to store your data. An array is an object where you can store information in a list-like order.

The Code

var arrayLit = []; //Array Literal
var arrayObj = new Array(); //Array instance using a constructor
Listing 7-1.
Creating Array Literals and Instances of an Array Object

How It Works

In all instances, you get an array with all the properties and methods of an array . Using the array literal is a quick way of building an array and is considered an easy-to-read way of generating an array. Using the array constructor gives you the option of either setting the length of the array or passing values to it. Items in the array are not of any specific type.
Unlike with other languages, an array is not fixed. It can grow or shrink depending on your needs. If you pass a number to the constructor, you can set the length of an array; however, you can continue to add items past that original number. Arrays can be created using a constructor or you can create an array literal using the bracket syntax.
JavaScript refers to each value in an array as an element. Elements are zero-based, meaning that the first element in the array uses the index number of zero to access it. You will see how this is done in the next section.

How Do You Access Elements in an Array?

Problem

You need to access elements in the array and get their values.

Solution

You access each element of the array by its index number using the bracket syntax.

The Code

var dayArray = new Array('monday', 'tuesday', 'wednesday'];
dayArray[0] //returns monday
dayArray[3] //returns undefined
Listing 7-2.
Returning the Value of an Element in the Array

How It Works

Elements in an array are zero-based. To access them, you need to use bracket syntax with a number. This number must not exceed the amount of items in the array. If you ask for a value that is not defined in the array, it will return undefined.

How Do You Create a Multi-Dimensional Array ?

Problem

You want to keep track of the contents of a table, whereby one dimension represents rows and the other columns.

Solution

There isn’t any special syntax to create a multi-dimensional array. You do this by adding a new array inside an element of another array. You can also create a multi-dimensional array with array literals.

The Code

var multiArray = new Array();
    multiArray[0] = new Array();
var litMultiArray = [[1,2], 3, 4];
Listing 7-3.
Creating a Multi-Dimensional Array

How It Works

Multi-dimensional arrays are very similar to regular arrays. Accessing an element would mean first accessing the outer array, then the element in the inner array . For example, multiArray[0][1] would be the first item on the outer array and the second item in the inner array.

How Do You Initialize an Array with Values ?

Problem

You need to create an array with values set upon initialization.

Solution

Using either array literals or a constructor, you can pass values into the array.

The Code

var itemArray = new Array('item 1', 'item 2', 'items 3');
var itamArrayLit = ['item 1', 'item 2', 'item 3'];      
Listing 7-4.
Creating Arrays with Values

How It Works

When using a constructor, make sure to pass more than one value. If you pass a single number into the constructor, it will think that you want to set the length of the array . A comma-separated list of numbers would be treated as values that would go into the array. If creating an array literal, you do not have this problem. All values will become elements in the array.

What Is the Size of the Array ?

Problem

You want to know how many elements are in the array.

Solution

Use the length property.

The Code

var weekArray = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
 console.log(weekArray.length);
Listing 7-5.
Determining the Size of an Array Using the Length Property

How It Works

The length property gives the number of items in an array. Since arrays are zero-based, the first item in the array is zero. This is important to remember because, if the length is seven, like in Listing 7-5, that means there are seven items total, starting from zero to six.

How Do You Convert an Array to a String?

Problem

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

Solution

There are multiple ways to convert an array to a string. Two ways are the toString() method and the join() method .

The Code

numberArray = [1, 2, 3, 4, 5, 5, 6, 7, 8, 9];  // returns [1, 2, 3, 4, 5, 5, 6, 7, 8, 9]
console.log( numberArray.toString() ); //returns 1,2,3,4,5,6,7,8,9
console.log( numberArray.join('') );  //returns 123456789
console.log( numberArray[0].toString() );  //returns 1
Listing 7-6.
Converting an Array to a String Using toString and Join

How It Works

The toString() method will create a comma-separated string based on all the elements in the array. You can also take a single element and convert that into a string.
The join method will convert all the elements in the array into a single string without commas.

How Do You Add an Element to the End of an Array?

Problem

You want to add an extra element to the end of an array.

Solution

The push() method will automatically add an element to the end of an array. It is also important to note that it does not account for gaps in the array. For example, if you create an element with no value, then use the push method, it will create a new element after the blank one.

The Code

var weekArray = ['Sunday', 'Monday', 'Tuesday'];
    weekArray.push('Wednesday');
    weekArray[4] = 'Thursday';
//result is now ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday']
Listing 7-7.
Using the push() Method to Add to an Existing Array

How It Works

Using the push() method , you can add one or more elements to the current array. This method will return the new length of the array. Mixing the push method and naming an element specifically can create gaps in the array by accident. If you consistently use the push method, you will always add one more value to the array without the possibility of creating gaps.

How Do You Add Items to an Array Within a Range?

Problem

You want to give the array values in a certain range.

Solution

Using the fill() method , you can add a value with a start and end index number.

The Code

var numberArray = [1,2,3,4];
    numberArray.fill(5, 0, 1);
console.log(numberArray); //result [5, 2, 3, 4]
Listing 7-8.
The Fill Method Will Add a Value Based on the Start and Ending Index Numbers

How It Works

The fill() method will add a value given to your array. Two optional parameters are the start and end indexes. When given these parameters, you can update values based on the index number.

How Do You Append an Array to the End of Another Array?

Problem

You need to combine the values of two arrays into one single array.

Solution

Use the concat() method to combine one array to the end of the other.

The Code

var numberArray = [1,2,3,4];
var numberArray2 = [5,6,7,8];
var resultArray = numberArray.concat(numberArray2);
console.log(resultArray);
Listing 7-9.
Appending the Values of an Array to Another Array

How It Works

The concat() method returns a new array with the elements of the original array and the elements of the array being used in the argument as long as the argument is an array. This does not alter the original arrays. What this method does is make a shallow copy that contains references to the original arrays. This is important because if the reference or copy object is modified, the original array will also be modified.

How Do You Reverse the Order of the Items in an Array?

Problem

You want to reverse the order of the elements in your array.

Solution

Use the reverse() method to combine one array to the end of the other.

The Code

var numberArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
    numberArray.reverse();
console.log(numberArray);  //returns [9,8,7,6,5,4,3,2,1]
Listing 7-10.
Reversing Elements in the Array Using the Reverse Method

How It Works

In this example, the reverse method returns an array in place. The first element in the array becomes the last and the list will be the first element. This method mutates the array and returns a reference to the array.

How Do You Copy Elements Based on Their Position Inside an Array?

Problem

You have an array where you want to copy only the elements in a range to other elements in the same array.

Solution

Use the copyWithin() method to copy a rage of elements and use those values to replace other elements in the same array.

The Code

var numberArray = [1, 2, 3, 4, 5, 6];
console.log(numberArray.copyWithin(3, 0));  //returns [1, 2, 3, 1, 2, 3]
Listing 7-11.
Copying and Updating Elements in the Same Array

How It Works

Understanding the copyWithin() method can be a little confusing. This method takes three arguments—target, start, and end. All of these arguments are numbers. The end argument is optional; in that case, the browser will use the length of the array as the end value.
When discussing these parameters, target tells the browser which element in the array it should update. The start argument defines which element it should start copying. In Listing 7-11, the target element would be 3 (4 because arrays are zero-based) and then it will start copying from 0 (the first element). Since this example does not have an ending argument, it will copy the rest of the array and replace the elements in the array. This method does not have support in Internet Explorer, Opera, or Safari.

How Do You Add Multiple Items to the Beginning of an Array?

Problem

You need to add elements to the beginning of an array.

Solution

Use the unshift() method to push the elements back to make room for new elements in the front.

The Code

var numberArray = [4, 5, 6];
numberArray.unshift(1, 2, 3)
console.log(numberArray); //returns [1, 2, 3, 4, 5, 6]
Listing 7-12.
The unshift() Method Pushes All Elements Back to Make Room for New Ones

How It Works

The unshift() method will shift elements in array-like objects and place new elements in the front of the current elements. This method will return the new length of the array when finished.

How Do You Change the Contents of an Array by Adding or Removing Elements?

Problem

You need a quick way to change the elements in the array by adding or removing elements .

Solution

Use the splice() method to change the contents of an array.

The Code

var marxBros = ['Groucho', 'Harpo', 'Chico'];
marxBros.splice(2, 0, 'Zeppo');
console.log(marxBros); //returns ['Groucho', 'Harpo', 'Chico', 'Zeppo']
marxBros.splice(1, 3);
console.log(marxBros); //returns ['Groucho']
Listing 7-13.
The splice() Method Allows You To Add or Remove Elements of the Current Array

How It Works

When using splice, you need to pass over at least two arguments. The first argument, start, tells the browser where to start modifying the array. The next value describes how many items you would like to delete, called the deleteCount. The third optional argument would be a comma-separated list of items you would like to add to the array.
In Listing 7-13, we are deleting no items after the second element in the array, and then adding Zeppo to the array. After that, another splice call is made removing three elements after the first element, only leaving Groucho.

How Can You Simulate First-In First-Out Behavior ?

Problem

You want to treat your array like a stack and get the first element in the array .

Solution

The shift() method will return the first item in the array.

The Code

var marxBros = ['Groucho', 'Harpo', 'Chico'];
var shiftedItem = marxBros.shift();
console.log(shiftedItem); //returns ['Groucho']
Listing 7-14.
The shift() Method Will Remove the First Element from the Array

How It Works

The shift() method will remove the first item in the array (the item at index 0). It will then shift the rest of the items forward. This method changes the length of the array.

How Can You Simulate Last-In First-Out Behavior ?

Problem

You want to treat your array like a stack and get the last element in the array.

Solution

The pop() method will return the first item in the array.

The Code

var marxBros = ['Groucho', 'Harpo', 'Chico'];
marxBros.pop();
console.log(marxBros); //returns ['Groucho',  'Harpo']
Listing 7-15.
The pop() Method Will Remove the Last Element from the Array

How It Works

The pop() method will remove the last item in the array and return the value to the caller. Similar to the previous example, you can simulate a stack and, with this method, perform last in, first out (LIFO) operations.

How Do You Create a Smaller Array Based on the Values in a Range?

Problem

You want to create a variable that contains a portion of the current array.

Solution

The slice() method will return a shallow copy of the array based on the range you give it.

The Code

var albumNames = ['Hack', 'Violator', 'Designation', 'Wild', 'Surrender'];
console.log(ablumNames.slice(0,2)); //returns ["Hack", "Violator"]
Listing 7-16.
The slice() Method Returns Only the Elements in the Given Range

How It Works

This method returns a shallow copy of the array. That means that the copy is done by reference. The slice() method take two arguments, The first is the start index number, where the browser should start editing the array. The second argument is the end index number. In Listing 7-16, the slice starts with the first element and ends with element 2. The array returns all elements up to the end number.

How Do You Get the Index Number of a Value?

Problem

You have a value that belongs to an array but need the index number.

Solution

Using the indexOf() method will give you the first index of a value you pass to it. Or using lastIndexOf() will return the last index of the value you pass to it.

The Code

var albumNames = ['Hack', 'Violator', 'Designation', 'Wild', 'Surrender', 'Hack'];
console.log(ablumNames.indexOf('Hack')); //returns 0
console.log(ablumNames.lastIndexOf('Hack')); //returns 5
Listing 7-17.
Examples of indexOf() and lastIndexOf()

How It Works

These methods are useful if you know a value is being used more than once. For example, you may get results back from the server and lastIndexOf() can quickly give you the latest data. The reverse is also true. The indexOf() method would give you the first instance of the value given to it. If you do not get a result, these methods return -1.

How Do You Return the Index or Object Based on a Value in an Array?

Problem

You need either the value of an array or the index.

Solution

Use the find() method to get the value from an array and findIndex() to get the index number.

The Code

var albumCollection = [{album: 'Hack', artist: 'Information Society'}, {album: 'Violator', artist: ‘Depeche Mode'}, {album: 'Designation', artist: 'The Cure'}];
var foundAlbum = albumCollection.find( function(element, index, array){
           return element.album == 'Violator' })
console.log(foundAlbum); //returns Object {album: "Violator", artist: "Depeche Mode"}
var foundIndex = albumCollection.findIndex( function(element, index, array){
            return element.album == 'Violator'
});
console.log(foundIndex); //returns 1
Listing 7-18.
The Difference Between Find and FindIndex

How It Works

These methods work in a similar way that the map method works. You can assign a callback function to the method or use an anonymous function. In either case, you can run the function on each element of the array and evaluate it. If the test passes, you return the value or the index number from the array.
The callback function will receive the element, index number, and the array each time it’s called. There is an optional parameter that lets you set the value of this. These methods are not supported in Internet Explorer or Opera.

What Is a Spread Operator and How Does It Work?

Problem

You need to allow an undefined amount of arguments (for functions), elements (for arrays), or variables (for destructuring assignment).

Solution

The spread operator allows you to assign an unspecified amount of values.

The Code

function myValues(...values){
           return values
}
console.log(myValues(1,2,3)); // returns [1, 2, 3]
console.log(myValues(1,2,3,4,5,6)); // returns [1, 2, 3, 4, 5, 6]
var firstThree = ['One', 'Two', 'Three'];
var myArray = [...firstThree, 4, 5, 6];
console.log(myArray); // returns  ["One", "Two", "Three", 4, 5, 6]
[a ,b, ...otherShips] = ['Tardis', 'X-Wing', 'B-Wing', 'Enterprise', 'Moya']
console.log(otherShips); // returns ["B-Wing", "Enterprise", "Moya"]
Listing 7-19.
Using the Spread Operator on Functions, Arrays, and Variables

How It Works

The spread operator works in a similar way to the rest parameter. The main difference is the spread operator will let you express multiple values inside a single variable, whereas the rest parameter takes all values after the first one and expresses each value as an element in an array.
In these examples, there is a function that can take multiple arguments. The second takes the values of the first array and adds them to the second array. It is important to note that, without the dots (…), we would be creating a multi-dimensional array. In the third example, without the dots, the browser would just map the next value. The spread operator is available in Chrome, Firefox , and Microsoft Edge.

How Do You Take an Iterable Object and Convert It to an Array?

Problem

You have an object that you can iterate through and you want to convert into an array.

Solution

The Array.from() method can take an iterable object and convert it into an array.

The Code

function myValues(){
      return Array.from(arguments)      
}
console.log( myValues('one', 'two', 'three')); // returns ["one", "two", "three"]
Listing 7-20.
Returning an Array When Arguments Are Passed to the Function

How It Works

The from() method is a static method. Using it is similar to using a method of the Math class. This method can take three arguments, the second and third are optional. The first is the array-like object; the second is a map function.
This function works the same way as the map method. The function is executed on each element of the array. The third optional argument is the value that will set the value of this while the function is being executed. This method does not have support in Internet Explorer or Opera.

How Do Typed Arrays Work and What Makes Them Different from Regular Arrays?

Problem

You need to decide to use either a regular array or a typed array.

Solution

If you are working with raw binary data, use a type array.

The Code

document.querySelector('#fileInput').addEventListener('change', getFileInfo);
var fileReader = new FileReader();
    fileReader.addEventListener('load', showBuffer);
function getFileInfo(e){       fileReader.readAsArrayBuffer(e.target.files[0]); //creating the arrayBuffer based on the loaded file
};
function showBuffer(e){
      var bytes = new Uint8Array(e.target.result); //creating a typed array using the arrayBuffer
      console.log(bytes.length);
      console.log(bytes[0]);
      console.log(bytes[1]);  
}
Listing 7-21.
Loading a File Using the File API and Passing the ArrayBuffer to a Typed Array

How It Works

Typed arrays are designed to work with binary data. Unlike regular arrays that can hold multiple types of data, typed arrays only have the same type. In addition, typed arrays cannot have any empty values making them contiguous. Typed arrays do not have all the methods that normal arrays have, like push or pop, and the isArray() method will return false.
There are several APIs that support typed arrays. Web Workers, Media Source API, File API, Canvas, and XMLHttpRequest are just some of the APIs that provide support.
Typed arrays are one of two different types of views for an ArrayBuffer , the other being DataView. In this two-step process, the ArrayBuffer holds the binary data with no way to access its contents. Then the data gets passed into either a typed array or a DataView object. Once there, it can be read or changed. There is a list of different type array views. Based on the data you are working with, they come in the 8 ,16, 32, and 64 numeric types. For the full list, look at Mozilla’s site at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays .
In Listing 7-21, we load a file based on the File API. When the file is loaded, it is passed over to the fileReader object. There the file is read as an arrayBuffer. The arrayBuffer is then used in creating a Unit8Array. This typed array then can use some of the syntax of a regular array.
..................Content has been hidden....................

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