Arrays

Arrays in JavaScript are used to store multiple values in a single variable, offering a way to group related data. In this section, we will explore arrays, their manipulation, and their significance in JavaScript. Arrays are crucial for handling lists of items, and understanding how to work with them is essential for any JavaScript developer.

Desired Outcomes:

  • Comprehend the basics of JavaScript arrays and their importance in data handling.
  • Learn how to create arrays, access their elements, and modify them.
  • Master various array methods for adding, removing, and manipulating array elements.
  • Understand how to iterate over arrays using different methods like for, forEach, and array iteration methods like map and filter.
  • Get to know about multidimensional arrays and how to manipulate them.
  • Learn how to sort data within arrays.

JavaScript arrays are used to store multiple values in a single variable. To create an array, you can do it in the following way:

var arrayName = ["value1", "value2", "valueN"];

An array is a special variable that can contain multiple values within a single variable. To access a certain value within an array, you need to refer to the index of the desired value.

In the next example, a colors array is declared which contains names of certain colors.

var colors = ["Red", "Yellow", "Green"];

Since array indexing starts from zero (0), the first value is under index 0, the second under 1, the third under 2, etc. Which means that if you want to access the value "Yellow" from the above example, you would do it in the following way.

colors[1];
var color = colors[1];

Since arrays are a special type of objects, various types of data can be stored within arrays. For example, strings, numbers, objects, functions, and even arrays within arrays can be stored.

var myArray = ["Text", 10, true, function myFunction(){}, object, ["Text", 10, false]];

To access a certain array value within another array, you first need to put the index of the first array, then the index of the value of the second array.

console.log(myArray[5][2]); // false

It is also possible to return the number of elements in an array using the .length method. The syntax is as follows:

myArray.length

If you executed the .length method on the myArray variable from the previous example, it would return the value 6 since there are 6 elements in the array.

<script>
   var myArray = ["Text", 10, true, function myFunction(){}, object, ["Text", 10, false]];
   console.log(myArray.length); // 6
</script>

Arrays in JavaScript do not have a fixed size, unlike arrays in other programming languages. What this means is that the content of the array can be changed during execution, that is, arrays can be shortened or expanded.

Array functions

In JavaScript, arrays have functions which can be used to expand or shorten an array, to filter for specific values, to transform an array or to sort an array.

10.1.1. Expanding and Shortening Arrays

There are three different ways to expand an array:

  • push() method - inserting values at the end of the array and returning the total number of elements after insertion.
  • unshift() method - inserting values at the beginning of the array and returning the total number of elements after insertion
  • Inserting a value at an index that currently does not exist in the array. The array is automatically expanded so that the given index is correct.

There are two different ways to shorten arrays:

  • pop() method - deletes the last element within the array, shortens the array length by one, and returns the removed element as a result.
  • shift() method - deletes the first element of the array, shortens the array length, and returns the removed element as a result.

In the example below, all of the above methods for manipulating arrays are illustrated:

<script>
  var myArray = [0, 1, 2, 3, 4, 5];
  myArray.push(6, 7); // inserts 6 and 7 after the last element
  myArray.unshift(-2, -1); // inserts -2 and -1 before the first element
  myArray.pop(); // deletes the last element of the array and shortens the array length by 1
  myArray.shift(); // deletes the first element of the array and shortens the array length by 1
  myArray[8] = 9; // inserts number 9 at index 8 within the array  
  console.log(myArray); // [-1, 0, 1, 2, 3, 4, 5, 6, undefined, 8]
  console.log(myArray.length); // 9
</script>

In the example, the number 9 is inserted at index 8 within the array. Since the value at index 7 does not exist, it will return undefined.

10.1.2. Filtering an Array - filter()

The function filter() returns a new array of filtered elements that meet a certain condition. The filter() method creates a new array with all elements that pass the test implemented by the provided function.

filter() does not execute the function for array elements without values and doesn't change the original array.

Syntax:

array.filter(function(currentValue, index, arr){
  // Callback code
})

In this example, you can see a function to be run for each element in the array, function arguments are:

  • currentValue - required, the value of the current element
  • index - optional, the array index of the current element
  • arr - optional, the array object the current element belongs to.

Example:

var numbers = [1, 2, 3, 4, 5, 6];
var evenNumbers = numbers.filter(function(number) {
    return number % 2 === 0;
});
console.log(evenNumbers); // Output: [2, 4, 6]

In this example, filter is used to create a new array evenNumbers that contains only the even numbers from the original numbers array. The callback function passed to filter returns true for even numbers (where number % 2 === 0), hence those numbers are included in the new array.

10.1.3. Transforming an Array - map()

The map() method calls a callback function on every element of an array and returns a new array that contains the results.

The map() method takes two named arguments, the first one is required whereas the second one is optional.

Syntax:

const newArray = oldArray.map(function(currentValue, index, array) {
  //  Callback code
});

In this example, you can see a function to be run for each element in the array, function arguments are:

  • newArray - the new array that is returned
  • oldArray - the old array being operated on. This array will not be changed
  • currentValue - the current value being processed
  • index - the current index of the value being processed
  • array - the original array

Example:

var numbers = [1, 2, 3, 4, 5];
var squares = numbers.map(function(number) {
    return number * number;
});
console.log(squares); // Output: [1, 4, 9, 16, 25]

In this example, map() is used to create a new array of squares where each element is the square of the corresponding element in the numbers array. The provided callback function takes each element (number), squares it, and the map method constructs a new array with these squared values.

10.1.4. Reducing an Array - reduce()

The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value. The reduce() method executes a provided function for each value of the array (from left-to-right).

Syntax:

array.reduce(function(total, currentValue, currentIndex, arr)
{
  // Callback code
})

In this example, you can see a function to be run for each element in the array, function arguments are:

  • total: a required parameter and used to specify the initialValue, or the previously returned value of the function.
  • currentValue: a required parameter and used to specify the value of the current element.
  • currentIndex: an optional parameter and used to specify the array index of the current element.
  • arr: an optional parameter and used to specify the array object the current element belongs to.
  • initialValue: an optional parameter and used to specify the value to be passed to the function as the initial value.
const numbersReduced = [1, 2, 3, 4, 5];
// The reduce function takes two parameters: an accumulator and the current element.
const sum = numbersReduced.reduce((accumulator, currentValue) => {
    return accumulator + currentValue;
}, 0); // 0 is the initial value of the accumulator

console.log(sum); // Output: 15

 

The reduce() method in this example takes an array of numbers and calculates their sum by sequentially adding each element to an accumulator, starting with an initial value of 0, and finally returns the total sum.

10.1.5. Sorting an Array - sort()

The sort() method sorts the elements of an array in place and returns the sorted array. The default sort is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.

Syntax:

arr.sort(function(firstElement, secondElement) {
  // Callback code
})

Parameters:

  • firstElement - the first element for comparison.
  • secondElement - the second element for comparison.

To sort an array of objects by the values of the object’s properties, you use the sort() method and provide a comparison function that determines the order of objects.

var numbers = [3, 1, 4, 1, 5, 9];
numbers.sort(function(a, b) {
    return a - b;
});
console.log(numbers); // Output: [1, 1, 3, 4, 5, 9]

In this example, sort() is used to sort the numbers array in ascending order. The callback function takes two arguments (a and b, the elements being compared). The function return a - b arranges the numbers in ascending order.

Working with arrays

In the following example, the user is asked to enter names of people until they stop the loop. The names are stored in an array using the push() method, while the do/while loop allows the names to be entered until the user stops the application.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>JS Input Persons</title>
    <script>
        function runApp() {
            var nameArray = [];
            var entry = "";
            do {    
                var name = prompt("Person's name:","");
                if (name != null)
                    nameArray.push(name);
                else {
                    alert("The application has been stopped!");
                    return;
                }
                entry = prompt("Would you like to enter more people (y/n)?", "y");
                if (entry == null) {
                    alert("The application has been stopped!");
                    return;
                }
            } while (entry.toLowerCase() == "y");

            var numberOfPeopleEntered = nameArray.length;
            nameArray.sort();
            var display = "You've entered " + numberOfPeopleEntered + " people";
            display += "\n\n";

            for (var i = 0; i < numberOfPeopleEntered; i++) {
                display += nameArray[i] + "\n";
            }
            alert(display);
        }
    </script>
</head>
<body>
    <h1>JS Input persons into array</h1>
    <a href="#" onclick="runApp()">RUN APP</a>
</body>
</html>

After the user has entered the desired number of names and stopped execution, the names are displayed in an alert() window.

Updated on:

Part of our complete: JavaScript Fundamentals guide

Want exercises and real projects for this lesson? Get the full course.