Skip to content

Arrays

JavaScript arrays are collections that can store multiple values in a single variable. Also, items are stored in a specific order. We can create an array in several ways:

  • using the Array and the new keyword
  • using square brackets, i.e. the characters [ and ].

Below we can see how to create such an Array:

const emptyArray = [];
const arrayWithNumbers = [1, 2, 3, 4];
const arrayWithStrings = ['John', 'Peter', 'Daniel', 'George'];
const arrayWithNew = new Array(1, 2, 3);

Since JS is not a strongly typed language, an array can store values of different types, e.g.:

function simpleFunction() {
    console.log("This is SDA'a array knowledge section");
}
const differentElements = [1, "Adam", simpleFunction]; // three-element array

After creating an array using one of the previously specified structures, it is filled with the indicated values, i.e. each subsequent cell contains the given value in a sequence. We can read the content of a given cell by entering its index in square brackets, e.g .:

const numbers = [1, 2, 3, 4];
numbers[0]; // first element of the array -> 1
numbers[3]; // fourth element of the array -> 4

Arrays are indexed from 0, so the first element of the array has index - 0, second - 1, third - 2, and so on.

The length property

The array's length property returns its size, for example:

const numbers = [1, 2, 3, 4];
console.log(numbers.length); // The console will display 4 because the array has four items.

const emptyArray = new Array(5);
console.log(emptyArray.length); // The console will display 5.

Arrays are objects that have a rich API. Some of the useful methods are:

  • push - adding a new item
  • pop - remove the last item, then return that item
  • shift - remove the first item from the array and then return that item
  • unshift - adds an element to the beginning of the array
  • join - joining successive elements into one text
  • reverse - reverse array elements
  • sort - sorting array elements
    • this method, in an argumentless overload, sorts the elements of an array naturally
    • has the option of specifying a sorting function which, based on two input elements, provides information whether one element should be before the other
  • concat - combines arrays (any number of them, we use the so-called varargs) and returns a new one, which is a combination of all of them
  • forEach - allows you to perform a specific function on each element of the array
  • map - creates a new array containing the results of calling the specified function for each element of the calling array
  • includes - checks if the array contains the given item
  • filter - Returns a new array with elements that meet the test specified in the function
  • indexOf - returns the first index containing the given value. Returns -1 if the item is not in the array.
  • slice - creates a copy of part of an array and returns it as a new array. It takes two arguments - beginning and end. Does not copy the index specified in end.
  • splice - modifies the array by removing elements and adding new ones. If we don't provide new elements, splice will only delete the old ones. It takes the start, the number of removed items and the items added.

The following examples show the use of these methods:

const numbers = [1, 2, 3];
numbers.push(4); // [1, 2, 3, 4]
const numbers = [1, 2, 3, 4];
numbers.pop();
numbers.pop(); // in the array the following will remain[1, 2]
const numbers = [1, 2, 3, 4];
const firstElem = numbers.shift(); // firstElem has value 1
const numbers = [1, 2, 3, 4];
numbers.unshift(5); // [5, 1, 2, 3, 4]
const numbers = [1, 2, 3, 4];
const output = numbers.join(','); // output has value: '1,2,3,4'
const numbers = [1, 2, 3, 4];
const reversed = numbers.reverse(); // reversed contains the array [4,3,2,1]
const strings = ['hello', 'hi', 'veryLongOne', 'i'];
strings.sort((strA, strB) => {
  if (strA.length === strB.length) {
    return 0;
  }
  if (strA.length < strB.length) {
    return -1;
  }
  return 1;
}); // the result will be a sorted list: ["i","hi","hello","veryLongOne"]
[1].concat([2, 3], [4, 5]); // [1, 2, 3, 4, 5]
['one', 'two', 'three', 'four'].forEach((element, index) => { console.log(`element on index ${index} is \'${element}\'`); });

/* The following will be displayed on the console:
element on index 0 is 'one'
element on index 1 is 'two'
element on index 2 is 'three'
element on index 3 is 'four'
*/
['one', 'two', 'three', 'four'].map((elem) => elem.length); // output will be [3, 3, 5, 4]
[1, 2, 3, 4].includes(3, 3); // false
[1, 2, 3, 4].slice(1, 2); // the following array will be returned [2]
let numbers = [1, 2, 3, 4, 5];
const returnedValue = numbers.splice(1, 3);
console.log(numbers); // [1, 5]
console.log(returnedValue); // [2, 3, 4]