Advanced Array Manipulation - Advanced JavaScript - JavaScript, 20 Lessons to Successful Web Development (2015)

JavaScript, 20 Lessons to Successful Web Development (2015)

PART II Advanced JavaScript

LESSON 9 Advanced Array Manipulation

image

To view the accompanying video for this lesson, please visit mhprofessional.com/nixonjavascript/.

In this final lesson on JavaScript arrays, we finish off our exploration by looking at how to sort the contents of arrays in a variety of different ways and how to manipulate groups of elements within arrays, including removing, inserting, and moving them.

Using sort()

JavaScript comes with a handy sort() function to sort arrays alphabetically in ascending order with case sensitivity. Like reverse(), this function changes the actual array to which it is applied, unlike some other functions that simply return a new array, leaving the original untouched.

To sort an array, simply call the sort() function on the array, as with this example that uses the Cats array:

image

The result of issuing this sort() call (the code for which is available as sort.htm in the companion archive) is shown in Figure 9-1.

image

FIGURE 9-1 Sorting an array alphabetically

Tailoring the sort() Function

If all you require is a case-sensitive alphabetical sort in ascending order, sort() is just the function for you. However, should you need to sort in reverse order or sort an array numerically, you need to provide some extra code to sort() to help it achieve this.

image

Enhancing the sort() function requires using functions that you will write, so because I don’t properly cover functions until Lesson 12, if the following makes you scratch your head, remember that you can simply copy and paste the code and it will work anyway, without you having to know (yet) just how it works.

Sorting Numerically

When an alphabetical sort is used, numbers are treated as strings so that, for example, the number 200 will come before the number 3 (because 2 comes before 3). In order to sort an array numerically, you must pass a helper function to the sort() function. This helper needs to tell sort() how to compare pairs of items as it sorts. Therefore, to sort an array numerically in ascending order, you can supply a function such as this:

image

What this function does is accept two array elements (for example, it might be elements 0 and 1) and then it tests whether the first element is greater than the second by subtracting the second from the first.

If the result of this subtraction is greater than 0, b is smaller than a. Or, if it’s less than 0, b is greater than a; otherwise, they have the same value. Therefore, what gets returned by SortNumeric() is either a negative, a zero, or a positive value, from which the sort() function decides the order in which to place the two elements, as follows:

• If the result returned by SortNumeric() is negative, b is greater than a, and therefore the element represented by a must appear before the one represented by b.

• If the result is positive, b is smaller than a, and so the element represented by b must appear before that represented by a.

• If the values in a and b are equal, there is no need to change the positions of the elements represented by a and b, so nothing happens.

The SortNumeric() function is passed to the sort() function, like this:

Numbers = [7, 62, 3, 99, 74, 11, 16, 1]
Numbers.sort(SortNumeric)

The first statement creates the array Numbers, in which a variety of different numeric values are stored. Then the second statement calls the sort() function on that array, passing it the name of the helper function to use (namely SortNumeric), but omitting the parentheses that usually follow a function name.

This is because we are telling sort() which function to use and not passing it the result of calling the function (more on this in the following lesson). The result of running this code is shown in Figure 9-2.

image

FIGURE 9-2 Sorting an array numerically

At the expense of readability, if you wish, you can bypass the requirement for creating a function to perform the sort by including an inline anonymous (unnamed) function as the argument to the sort() function instead, as with the following example that sorts the Numbers array numerically in ascending order:

Numbers.sort(function(a, b) { return a – b })

Reversing a Sort

To obtain a reversed sort of any kind, all you need to do is pass the sorted array to the reverse() function, like this (as shown in Figure 9-3):

Cats.sort().reverse()

image

FIGURE 9-3 Reversing a sorted array

image

You will probably have realized that for numeric arrays the expression return a - b in the SortNumeric() function could be replaced with return b - a, which would also result in a reversed sort—one example of how you can achieve the same outcome in JavaScript using different methods.

Using splice()

I’ve left possibly the most powerful array function, splice(), until last—not just because it comes last alphabetically, but because you can use it to provide the same facility as most of the other array functions, and a lot more too.

With splice() you can remove one or more elements from an array, or insert one or more into an array, and you can do either at any position within the array. What’s more, you can remove and insert at the same time, providing a replace facility that can swap one or more elements with more, the same, or fewer elements.

Removing Elements from an Array

Let’s look first at how to remove one or more elements from an array, starting with the Cats array we’ve been using a lot. In the following example, the splice() function is called with two arguments. The first is the element at which to perform the splice (starting from 0), and the second is the number of elements to be removed:

image

Therefore, with arguments of 2 and 3, the splice starts at the element index 2, which is the third element, and the second argument of 3 states that three elements are to be removed from the array. If you need to know which elements have been removed, you can access the result of calling the function, which is an array containing the removed elements, like this:

Removed = Cats.splice(2, 3)

Figure 9-4 shows this code brought together, displaying the array before splicing, the elements removed by the splice, and the elements remaining afterward.

image

FIGURE 9-4 Removing elements from an array

Inserting Elements into an Array

Using a similar call to splice(), you can insert new values into the array, as in the following example, which adds two more breeds of cat starting at the third element:

Cats.splice(2, 0, ′Siamese′, ′Persian′)

Here, the first argument of 2 is the third element in the array, and the second argument of 0 tells splice() that there are no elements to be removed. After this there are two new arguments, which tell splice() to insert them into the array starting at element 2 (the third one). You may place as many values as you like here to insert as many new elements as you need. The result of making this call is shown in Figure 9-5.

image

FIGURE 9-5 Inserting values into an array

Advanced Array Splicing

Finally, you can remove and insert elements at the same time, using a call such as the following:

Cats.splice(2, 3, ′Siamese′, ′Persian′)

This statement tells splice() to use a splice index of 2 (the third element), at which location it must remove three elements and then insert the new values supplied. The result of issuing this call is shown in Figure 9-6.

image

FIGURE 9-6 Removing from and inserting items into an array

Example files are available in the companion archive demonstrating all three types of splicing. They are splice.htm, insert_splice.htm, and advanced_splice.htm.

Summary

You now know how to use all types of JavaScript arrays, whether single- or multidimensional, numeric, string, associative, or otherwise. Coupled with your earlier knowledge of variables and operators, you are now ready to really get down to some power programming, beginning withLesson 10 on controlling program flow.

Self-Test Questions

Using these questions, test how much you have learned in this lesson. If you don’t know an answer, go back and reread the relevant section until your knowledge is complete. You can find the answers in Appendix A.

1. How can you sort an array alphabetically in ascending order?

2. How can you sort an array alphabetically in descending order?

3. How can you sort an array numerically in ascending order using an external function?

4. How can you sort an array numerically in descending order using an external function?

5. How can you sort an array numerically in ascending order using an inline anonymous function?

6. How can you sort an array numerically in descending order using an inline anonymous function?

7. With which function can you insert and remove elements from an array in the same command?

8. What does the command fruits.splice(4, 2) do?

9. What does the command fruits.splice(5, 0, ′Apples′, ′Pears′) do?

10. What does the command fruits.splice(6, 2, ′Apples′, ′Pears′, ′Grapes′) do?