Skip to main content

Arrays

I. Introduction to Arrays​

Resources:

An array is an ordered collection of items (strings, numbers, etc). If you have a list of items, you can store them in an array.

1. Array Literal Notation​

Array Literal Notation is the most common and recommended way to create arrays.

// syntax
// it's a common practice to declare arrays with const
const arrayName = [item1, item2, ...];

2. Array Constructor - Array()​

The Array constructor is a special[[01. Objects and Object Constructor#II. Object constructors | object constructor]] built into JavaScript's core. Arrays in JavaScript are actually objects that inherit from Array.prototype.

  • Because it’s a special constructor, it behaves the same way whether you use the new keyword or not.
  • This constructor is an exception to the rule, NOT the norm. For most constructors you should always use the new keyword.
// using the Array() constructor 
// creates an array and assigns values to it
const cars = new Array("Honda", "Toyota", "Mitsubishi");

// both of these ways work
const cars = Array("Honda", "Toyota", "Mitsubishi");

// equivalent to
const cars = [
"Honda",
"Toyota",
"Mitsubishi"
];

// creates an array with length of 40, but doesn't populate elements
const points = new Array(40);
console.log(points.length); // 40
console.log(points);

2. Accessing and Changing Array Elements​

// you can access array elements through index numbers
console.log(cars[0]); // "Honda"
console.log(cars[1]); // "Toyota"
console.log(cars[2]); // "Mitsubishi"

// you can change the value of at the specified index
cars[2] = "Acura";

console.log(cars); // ["Honda", "Toyota", "Acura"]
Associative Arrays
  • Many programming languages support arrays with named indexes. Arrays with named indexes are called associative arrays (or hashes).
  • JavaScript does NOT support arrays with named indexes. In JavaScript, arrays always use numbered indexes.

If you use named indexes, JavaScript will redefine the array to an object because

  • In JavaScript, arrays use numbered indexes.  
  • In JavaScript, objects use named indexes.

Negative Index: Many languages (e.g. Python) allow negative bracket indexing like [-1] to access elements from the end of an object/array/string. This is not possible in JavaScript.

3. Arrays are Objects in JavaScript​

Arrays are a special type of [[11. Objects|object]]. But, JavaScript arrays are best described as arrays.

// arrays use "index numbers" to access its elements
const students = ["A", "B", "C"];
console.log(students[0]); // A

// objects use "keys" to access their value
const person = {
firstName: "John",
lastName: "Doe",
age: 46
};
console.log(person.firstName); // John

6. Array Elements of Different Types​

You can have variables of different types in the same Array. You can have numbers, strings, objects, functions, even arrays in an Array.

const mixed = [1, 2, "Hello?", Date.now, myFunction, [2, 3, 4]]; 

II. Array Basic Properties and Methods​

Resource

1. length property​

Returns the length of an array (the number of array elements).

const fruits = ["Banana", "Orange", "Apple", "Mango"]; 
console.log(fruits.length); // 4

// using length to access the last array element
let lastFruit = fruits.[fruits.length - 1];

2. push() and pop()​

  1. The easiest way to add a new element to the end of an array is using the push() method.
    • A new element can also be added to an array using the length property.
const fruits = ["Banana", "Orange", "Apple"];  

// push()
fruits.push("Lemon");  // Adds a new element (Lemon) to fruits

fruits[fruits.length] = "Lemon";  // Adds "Lemon" to fruits
  1. The pop() method removes the last element from an array. The pop() method returns the value that was “popped out”.
const fruits = ["Banana", "Orange", "Apple", "Mango"];  
let fruit = fruits.pop();

console.log(fruits); // ["Banana", "Orange", "Apple"]
console.log(fruit); // "Mango"

3. at() method​

Accesses the value at the specified index number.

const fruits = ["Banana", "Orange", "Apple", "Mango"];  
console.log(fruits.at(2)); // Apple
// equivalent to accessing element by index
console.log(fruits[2]); // Apple

4. shift() method​

Removes the first element of the array and “shifts” all the other elements to a lower index. The shift() method returns the value that was "shifted out":

const fruits = ["Banana", "Orange", "Apple", "Mango"];  
let fruit = fruits.shift();

console.log(fruits); // ["Orange", "Apple", "Mango"]
console.log(fruit); // "Banana"

5. unshift() method​

Adds a new element to the beginning of the array and unshifts older elements. The unshift() method returns the new array length:

const fruits = ["Banana", "Orange", "Apple", "Mango"];  
let newLength = fruits.unshift("Lemon");

console.log(fruits); // ["Lemon", "Banana", "Orange", "Apple", "Mango"]
console.log(newLength); // 5

6. delete()​

Using delete() leaves undefined holes in the array. Use pop() or shift() instead to remove elements from an array.

const fruits = ["Banana", "Orange", "Apple", "Mango"];
delete(fruits[0]);
console.log(fruits[0]); // undefined

7. concat() method​

Creates a new array by concatenating existing arrays, it can take any number of array arguments. The concat() method does NOT change existing arrays, it always returns a new array.

const myGirls = ["Cecilie", "Lone"];  
const myBoys = ["Emil", "Tobias", "Linus"];

const myChildren = myGirls.concat(myBoys);
console.log(myChildren); // ["Cecilie", "Lone", "Emil", "Tobias", "Linus"]

// concatenate 3 arrays
const arr1 = ["Cecilie", "Lone"];
const arr2 = ["Emil", "Tobias", "Linus"];
const arr3 = ["Robin", "Morgan"];

const myChildren = arr1.concat(arr2, arr3);
/* ['Cecilie', 'Lone', 'Emil', 'Tobias', 'Linus', 'Robin', 'Morgan'] */
  • The concat() method can also take strings/numbers as arguments:
const names = ["Emil", "Tobias", "Linus"];
const newNames = names.concat("Peter");
console.log(newNames); // ["Emil", "Tobias", "Linus", "Peter"];

const namesAndNumber = newNames.concat(1, 2, 3);
console.log(namesAndNumber); // [ 'Emil', 'Tobias', 'Linus', 'Peter', 1, 2, 3 ]

8. flat() method​

Creates a new array with sub-array elements concatenated to a specified depth.

const myArr = [[1,2],[3,4],[5,6]];  
const newArr = myArr.flat();
console.log(newArr); // [1, 2, 3, 4, 5, 6]

9. splice() method​

Can be used to add/remove new items to an array. The method can take up to three arguments:

  • the first parameter defines the index position where new elements would be added
  • the second parameter defines how many elements should be removed
  • the rest of the parameters define the new elements to be added The splice() method returns an array with the deleted items.

Example 1:

const fruits = ["Banana", "Orange", "Apple", "Mango"];  
let deletedFruit = fruits.splice(2, 1, "Lemon", "Kiwi");

console.log(fruits); // ["Banana", "Orange", "Lemon", "Kiwi", "Mango"]
console.log(deletedFruit); // ["Apple"]

Example 2: Removing elements without leaving “holes in the array”. There are only two parameters here because no new elements will be added.

const fruits = ["Banana", "Orange", "Apple", "Mango"];  
let deletedFruit = fruits.splice(0, 1);

console.log(fruits); // ["Orange", "Apple", "Mango"];
console.log(deletedFruit); // ["Banana"]

10. toSpliced() method​

The difference between the new toSpliced() method and the old splice() method is that the new method creates a new array, keeping the original array unchanged, while the old method alters the original array.

const months = ["Jan", "Feb", "Mar", "Apr"];  
const spliced = months.toSpliced(0, 1); // removing 1 element starting from index 0

console.log(months); // ["Jan", "Feb", "Mar", "Apr"]
console.log(spliced); // ["Feb", "Mar", "Apr"]

11. slice() method​

Slices out a piece of an array into a new array. It creates a new array containing the sliced elements and does not remove any elements from the source array. The method takes in the starting and (up to but not included) ending index number.

const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];  
const randomFruits = fruits.slice(1); // from index 1 till the end

console.log(randomFruits); // ["Orange", "Lemon", "Apple", "Mango"]
console.log(fruits); // ["Banana", "Orange", "Lemon", "Apple", "Mango"]
const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];  
const citrus = fruits.slice(1, 3); // [ "Orange", "Lemon" ]
// from index 1 up to 3 (but not included)

12. toString() method​

All JavaScript objects have a toString() method. JavaScript automatically converts an array to a comma-separated string when a primitive value is expected.

const fruits = ["Banana", "Orange", "Apple", "Mango"];
const fruitString = fruits.toString();

console.log(fruitString); // Banana,Orange,Apple,Mango

13. join() method​

Joins all array elements into a string, behaves just like toString(), but in addition you can specify the separator.

const fruits = ["Banana", "Orange", "Apple", "Mango"];  
const fruitString = fruits.join(" * ");

console.log(fruitString); // Banana * Orange * Apple * Mango

III. Array Search Methods​

Resource

1. indexOf() method​

Searches an array for an element value and returns its index number position.

const fruits = ["Apple", "Orange", "Apple", "Mango"];  
let indexNumber = fruits.indexOf("Apple");
console.log(indexNumber); // 0

2. lastIndexOf() method​

The same as indexOf() but returns the position of the last occurrence of the specified element.

const fruits = ["Apple", "Orange", "Apple", "Mango"];
let lastIndexNumber = fruits.lastIndexOf("Apple");
console.log(lastIndexNumber); // 2

3. includes() method​

Checks if an element is present in an array.

const fruits = ["Banana", "Orange", "Apple", "Mango"];  

console.log(fruits.includes("Mango")); // true
console.log(fruits.includes("Lemon")); // false

4. find() method​

The find() method takes a callback function as an argument. It returns the value of the first array element that passes a test function.

const numbers = [4, 9, 16, 25, 29];  
let firstOver18 = numbers.find(myFunction);

function myFunction(value) {
  return value > 18;
}

// equivalent arrow function
let firstOver18 = numbers.find(value => value > 18);

console.log(firstOver18); // 25

IV. Array Sort Methods​

Resource

1. sort()method​

Sorts an array alphabetically.

const fruits = ["Banana", "Orange", "Apple", "Mango"];  
fruits.sort();
console.log(fruits); // ["Apple", "Banana", "Mango", "Orange"]

By default, the sort() function sorts values as strings. If numbers are sorted as strings, "25" is bigger than "100", because "2" is bigger than "1". → Because of this, the sort() method can produce incorrect results when sorting numbers.

To sort numbers in an array, we should use the comparison function.

Compare Function​

The sort() method can take a comparison function as an optional parameter.

The purpose of the compare function is to define an alternative sort order. The compare function should return a negative, zero, or positive value, depending on the arguments:

function sortAscending(a, b){
return a - b;
}

// equivalent arrow function
(a, b) => a - b
  • If the result is negative, a is sorted before b.
  • If the result is positive, b is sorted before a.
  • If the result is 0, no changes are done with the sort order of the two values.
// using with sort() for numeric sort
// also using arrow function
const points = [40, 100, 1, 5, 25, 10];
points.sort((a, b) => a - b);
console.log(points); // [ 1, 5, 10, 25, 40, 100 ] -> ascending order

// Descending order sort using comparison function
points.sort((a, b) => b - a);
console.log(points); // [ 100, 40, 25, 10, 5, 1 ] -> descending order

2 .reverse() method​

Reverses the elements in an array.

const fruits = ["Banana", "Orange", "Apple", "Mango"];  
fruits.reverse();
console.log(fruits); // ["Mango", "Apple", "Orange", "Banana"]

By combining sort() and reverse(), you can sort an array in descending order.

3. toSorted() method​

The difference between toSorted() and sort() is that the first method creates a new array, keeping the original array unchanged, while the latter method alters the original array.

const months = ["Jan", "Feb", "Mar", "Apr"];  
const sorted = months.toSorted();
console.log(sorted); // ["Apr", "Feb", "Jan", "Mar"]

4. toReverse() method​

The difference between toReversed() and reverse() is that the first method creates a new array, keeping the original array unchanged, while the last method alters the original array.

const months = ["Jan", "Feb", "Mar", "Apr"];  
const reversed = months.toReversed();
console.log(reversed); // ["Apr", "Mar", "Feb", "Jan"]

V. Array Iteration Methods​

Resource

1. forEach() method​

Iterate over elements of an array and execute a provided callback function once for each element.

  • For each iteration, the forEach() method invokes a callback function that you provide.
  • Inside the callback function, you define the operation or action to be performed on each element of the array. This callback function takes three arguments:
    • value: The current element being processed in the array.
    • index (optional): The index of the current element being processed.
    • array (optional): The array forEach() was called upon.
  • The forEach() method does not return anything.
const numbers = [45, 4, 9, 16, 25];  
let txt = "";

numbers.forEach(myFunction);
function myFunction(value) {
  txt += value + " ";
}

// equivalent arrow function
numbers.forEach(value => {
txt += value + " ";
})

console.log(txt); // 45 4 9 16 25

2. map() method​

Iterate over an array and apply a transformation or operation to each element, returning a new array containing the transformed elements

  • For each iteration, the map() function invokes a callback function that you provide.
  • Inside the callback function, you define the transformation or operation to be applied to each element of the array. This callback function takes three arguments:
    • value: The current element being processed in the array.
    • index (optional): The index of the current element being processed.
    • array (optional): The array map() was called upon.
  • The map() function returns a new array containing the results of applying the transformation to each element of the initial array.
const numbers1 = [45, 4, 9, 16, 25];  

const numbers2 = numbers1.map(myFunction);

function myFunction(value) {
  return value * 2;
}

// equivalent arrow function
const numbers2 = numbers1.map(value => value * 2);

console.log(numbers2); // [90, 8, 18, 32, 50]

3. filter() method​

Iterating over each element of an array and applying a specified condition to determine whether to include that element in a new array.

  • For each element, the filter() method evaluates a condition specified by a callback function that you provide.
  • This callback function is invoked for each element and returns a boolean value (true or false). This callback function takes three arguments:
    • value: The current element being processed in the array.
    • index (optional): The index of the current element being processed.
    • array (optional): The array filter() was called upon.
  • If the condition specified in the callback function evaluates to true for a particular element, that element is included in the new array.
const numbers = [45, 4, 9, 16, 25];  

const over18 = numbers.filter(myFunction);

function myFunction(value) {
  return value > 18;
}

// equivalent arrow function
const over18 = numbers.filter(value => value > 18)

console.log(over18); // [45, 25]

4.reduce() method​

Iterates through each array element to produce (reduce it to) a single value. The method works from left-to-right in the array. The method does not mutate the original array. reduce() takes two arguments:

  • callbackFunction: the function to run on each iteration
  • initialValue (optional but recommended, esp on non-number arrays): the starting value of the accumulator. If omitted, the first array element is used — but this can cause bugs on empty arrays or arrays of objects, so always provide it.
array.reduce(callbackFunction, initialValue)

Each iteration, the reduce() method invokes the callback function.

  • Inside the callback function, you define the operation to be applied to each element of the array and the accumulator value. This callback function takes four arguments:
    • accumulator: The accumulated value computed by the callback function.
    • value: The current element being processed in the array.
    • index (optional): The index of the current element being processed.
    • array (optional): The array reduce() was called upon.
  • The reduce() method returns the final accumulated value.
const numbers = [45, 4, 9, 16, 25];

// without arrow function
let sum = numbers.reduce(function(accumulator, value) {
return accumulator + value;
}, 0);

// equivalent arrow function
let sum = numbers.reduce((accumulator, value) => accumulator + value, 0);

console.log(sum); // 99

5. every() method​

Checks if all elements in an array satisfy a provided condition.

  • For each element in the array, the every() method invokes a callback function that you provide.
  • Inside the callback function, you define the condition to be checked for each element. The callback function takes three arguments:
    • value: The current element being processed.
    • index (optional): The index of the current element being processed.
    • array (optional): The array every() was called upon.
  • The method returns true if the condition holds true for every element in the array; otherwise, it returns false.
const numbers = [45, 4, 9, 16, 25];  
let allOver18 = numbers.every(myFunction);

function myFunction(value) {
  return value > 18;
}

// equivalent arrow function
let allOver18 = numbers.every(value => value > 18);

console.log(allOver18); // false

6. some() method​

Check if at least one element in an array satisfies a provided condition.

  • For each element in the array, the some() method invokes a callback function that you provide.
  • Inside the callback function, you define the condition to be checked for each element. The callback function takes three arguments:
    • value: The current element being processed.
    • index (optional): The index of the current element being processed.
    • array (optional): The array some() was called upon.
  • The method returns true if the condition holds true for at least one element in the array; otherwise, it returns false.
const numbers = [45, 4, 9, 16, 25];  
let someOver18 = numbers.some(myFunction);

function myFunction(value, index, array) {
  return value > 18;
}

// equivalent arrow function
let someOver18 = numbers.some(value => value > 18);

console.log(someOver18); // true

VI. Arrays & Spread Operator​

1. Expanding Arrays​

The spread operator allows you to expand arrays into individual elements, which is particularly useful for function arguments.

const numbers = [1, 2, 3];
console.log(...numbers); // Output: 1 2 3

// Without spread operator
function sum(a, b, c) {
return a + b + c;
}

// With spread operator
console.log(sum(...numbers)); // Output: 6

2. Copying Arrays​

One of the most common uses of the spread operator is to create a shallow copy of an array.

const originalArray = [1, 2, 3];
const copyArray = [...originalArray];

console.log(copyArray); // Output: [1, 2, 3]

// This is a true copy, not a reference
copyArray.push(4);
console.log(originalArray); // Output: [1, 2, 3] (unchanged)
console.log(copyArray); // Output: [1, 2, 3, 4]

3. Merging Arrays​

Combine multiple arrays into a single new array.

const array1 = [1, 2, 3];
const array2 = [4, 5, 6];

// Combining arrays
const combined = [...array1, ...array2];
console.log(combined); // Output: [1, 2, 3, 4, 5, 6]

// You can also insert arrays anywhere
const inserted = [0, ...array1, 3.5, ...array2, 7];
console.log(inserted); // Output: [0, 1, 2, 3, 3.5, 4, 5, 6, 7]

4. Converting Iterables to Array​

The spread operator can convert any iterable object to an array.

// String to array of characters
const str = "Hello";
const chars = [...str];
console.log(chars); // Output: ['H', 'e', 'l', 'l', 'o']

// Set to array
const uniqueNumbers = new Set([1, 2, 2, 3, 3, 4]);
const uniqueArray = [...uniqueNumbers];
console.log(uniqueArray); // Output: [1, 2, 3, 4]