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
newkeyword or not.- This constructor is an exception to the rule, NOT the norm. For most constructors you should always use the
newkeyword.
// 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 indexinglike[-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()
- 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
lengthproperty.
- A new element can also be added to an array using the
const fruits = ["Banana", "Orange", "Apple"];
// push()
fruits.push("Lemon"); // Adds a new element (Lemon) to fruits
fruits[fruits.length] = "Lemon"; // Adds "Lemon" to fruits
- The
pop()method removes the last element from an array. Thepop()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",