Lesson 23: Arrays Part 2
Learn advanced array operations in JavaScript to manipulate and work with collections of data.
23.1 Advanced Array Operations
In the previous lesson, we learned how to create arrays using the new operator. When we know the initial values, we can use a more concise syntax to declare arrays.
23.2 Initializing Arrays with Values
For example, consider the following student scores:
Name | Score |
---|---|
Alex | 50 |
Brian | 60 |
Carmen | 65 |
Dave | 75 |
Graham | 80 |
Keynes | 68 |
Morgan | 70 |
Olson | 85 |
We can declare two arrays to store this data:
const studentNames = [ "Alex", "Brian", "Carmen", "Dave", "Graham", "Keynes", "Morgan", "Olson" ]; const scores = [ 50, 60, 65, 75, 80, 68, 70, 85 ];
The array subscripts start at 0, so studentNames[0]
is "Alex", scores[0]
is 50, and so forth.
23.3 Performing Arithmetic Operations on Arrays
We can perform arithmetic operations on array values, such as calculating the sum and average:
Example 23.1: Calculating Scores
This example calculates the total and average scores from the scores array.
function calculateScores() { const scores = [50, 60, 65, 75, 80, 68, 70, 85]; let total = 0; for (let i = 0; i < scores.length; i++) { total += scores[i]; } const average = total / scores.length; return { total: total, average: average.toFixed(2) }; }
23.4 Displaying Array Data in Tables
We can dynamically generate HTML tables to display array data:
Example 23.2: Displaying Student Scores
This example creates a table to display student names and scores.
function displayScores() { const studentNames = [ "Alex", "Brian", "Carmen", "Dave", "Graham", "Keynes", "Morgan", "Olson" ]; const scores = [ 50, 60, 65, 75, 80, 68, 70, 85 ]; let tableHTML = ` <table class="data-table"> <thead> <tr> <th>Student</th> <th>Score</th> </tr> </thead> <tbody>`; for (let i = 0; i < studentNames.length; i++) { tableHTML += ` <tr> <td>${studentNames[i]}</td> <td>${scores[i]}</td> </tr>`; } tableHTML += ` </tbody> </table>`; return tableHTML; }
23.5 More Array Operations
Here are some additional useful array operations:
Example 23.3: Finding Highest and Lowest Scores
This example finds the highest and lowest scores in the array.
function findMinMaxScores() { const scores = [50, 60, 65, 75, 80, 68, 70, 85]; // Find highest score let highest = scores[0]; for (let i = 1; i < scores.length; i++) { if (scores[i] > highest) { highest = scores[i]; } } // Find lowest score let lowest = scores[0]; for (let i = 1; i < scores.length; i++) { if (scores[i] < lowest) { lowest = scores[i]; } } return { highest: highest, lowest: lowest }; }
Math.max()
and Math.min()
that can find maximum and minimum values when used with the spread operator: Math.max(...scores)
.