Skip to content

Arrays

Arrays in JavaScript are collections that can store multiple values in a single variable. In addition, elements are stored in a specific order. We can create an array in several ways:

  • using Array and the keyword new.
  • 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', 'Adam'];
const arrayWithNew = new Array(1, 2, 3);

Since JS is not a highly typed language, the 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

Once an array has been created with one of the previously given constructions, it is filled with the indicated values, meaning that each subsequent cell contains a successive value. Reading of the content of a given cell is achieved by giving it an index in square brackets:

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

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

Property length

The length property of an array returns its size, e.g:

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

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

Arrays are objects with rich API usage. Some useful methods include:

  • push - adds a new element
  • pop - delete the last element and then return this element
  • shift - remove the first element from the array and then return the element
  • unshift - adds an element at the beginning of the array
  • join - combining successive elements into one text
  • reverse - reversal of array elements
  • sort - sorting array elements
    • this method, in an non-argumental overload, sorts the array elements in a natural way
    • has the ability to provide a sorting function which, based on two input elements, provides information whether one element should be before the other.
  • concat - connects arrays (any number of them, we use so-called varargs) and returns a new one, which is a combination of them all
  • forEach - allows you to perform a specific function on each element of the array
  • map - creates a new array containing the results of the given function call for each element of the calling array
  • includes - checks that the array contains the element
  • filter - returns a new array of elements that meet the test specified in the function
  • indexOf - returns the first index on which the specified value is located. Returns a value of -1 if the element is not in an array.
  • slice - creates a copy of an array part and returns it as a new array. Accepts two arguments - beginning and end. Does not copy the index given in the end argument.
  • splice - modifies the array by removing elements and adding new ones. If we do not specify new elements, the splice will only remove the old ones. Accepts the start, number of items removed and 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(); // [1, 2] is left in the array
const numbers = [1, 2, 3, 4];
const firstElem = numbers.shift(); // firstElem equals to 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: '1,2,3,4'
const numbers = [1, 2, 3, 4];
const reversed = numbers.reverse(); // reversed contains 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 console will display:
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: [3, 3, 5, 4]
[1, 2, 3, 4].includes(3, 3); // false
[1, 2, 3, 4].slice(1, 2); // array [2] will be returned
let numbers = [1, 2, 3, 4, 5];
const returnedValue = numbers.splice(1, 3);
console.log(numbers); // [1, 5]
console.log(returnedValue); // [2, 3, 4]