Arrays in JavaScript are versatile data structures that allow you to store and manipulate collections of values. They are essential for handling lists of data, whether you're managing a series of numbers, strings, or more complex objects. To grasp the idea of arrays it is ok to imagine them as lists at first before you become more comfortable with them. They are ordered collections of elements, each identified by an index starting from 0. They are a type of object, which means they inherit properties and methods from the Object prototype.
Arrays
What are Arrays?
Creating Arrays
You can create arrays in several ways.
// Using array literals
let numbers = [1, 2, 3, 4];
// Mixed data types
let mixedArray = [1, 'Apple', true, [1, 2, 3], undefined];
// Using the Array constructor
let emptyArray = new Array(20); // Creates an array with 20 undefined elements
// For better readability, especially with long arrays, it's common to format them with indentation:
let myList = [
'apple',
'banana',
'cherry',
];
Checking for Arrays
There are three ways to check if a variable is an array.
// Assume the variable fruits is an array
Array.isArray(fruits); // Returns true
fruits instanceof Array; // Returns true
fruits.constructor === Array; // Returns true
Accessing and Modifying Elements
Elements in an array are accessed using their index.
let fruits = ['apple', 'banana', 'cherry'];
console.log(fruits[1]); // Outputs: banana
Attempting to access an index outside the bounds of the array returns undefined.
console.log(fruits[5]); // Outputs: undefined
You can modify elements directly.
fruits[1] = 'blueberry'; // Changes 'banana' to 'blueberry'
To add a new element at the end. This works because of the mismatch between length of an array and the indices. For instance a 10 item list will have a length of 10, but will go from index 1 to index 9. Therefore index 10 will be an addition to the end.
fruits[fruits.length] = 'date';
To remove an element but leave a hole in the numbering.
delete fruits[index];
Iterating Through Arrays
A common way to iterate through arrays is using a for loop. You can see more about for loops on its own page.
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
You can also use methods such as
forEach. Here 'fruit' is a temporary variable assigned to represent "thing in
the list" and could take any name and still work.
fruits.forEach(function(fruit) {
console.log(fruit);
});
Nested Arrays
Arrays can contain other arrays. This array contains a list of 2 lists which each have 2 values. To access an
element in a nested array use the syntax
arrayName[indexOfOuterList][indexOfInnerList].
let matrix = [
[1, 2],
[3, 4],
];
console.log(matrix[1][0]); // Outputs: 3 which the index 0 item of the index 1 list.
Spread Operator
The spread operator (…) allows you to expand elements of an array.
let newFruits = [...fruits, 'kiwi'];
This is particularly useful for copying arrays.
let copyFruits = [...fruits];
Without the spread operator, assigning one array to another would reference the same array and changing this 'copy' would impact the original.
let sameFruits = fruits;
sameFruits.push('lemon');
console.log(fruits); // 'lemon' is added to the original array
Rest Operator
The rest operator (…rest) collects all remaining arguments into an array. This is useful when the number of arguments is unknown.
function listFruits(first, ...rest) {
console.log(first);
console.log(rest);
}
listFruits('apple', 'banana', 'cherry');
// Outputs:
// apple
// ['banana', 'cherry']
Destructuring Assignment
Destructuring assignment is a convenient way to extract values from arrays or properties from objects into separate variables, all in a single line of code.
let [var1, var2, var3] = arr;
// This assigns the first three values from arr to var1, var2, and var3.
let colors = ['red', 'green', 'blue'];
let [first, second, third] = colors;
console.log(first); // 'red'
console.log(second); // 'green'
console.log(third); // 'blue'
You can skip a value by leaving an empty slot.
let [, , var1, var2] = arr;
// Skips the first two items and assigns the third and fourth to var1 and var2.
let numbers = [10, 20, 30, 40, 50];
let [, , third, fourth] = numbers;
console.log(third); // 30
console.log(fourth); // 40
Using the rest operator, you can collect the remaining values into a new array.
let [var1, var2, ...var3] = arr;
// Assigns the first two values to var1 and var2, and the rest to var3.
let fruits = ['apple', 'banana', 'cherry', 'date'];
let [first, second, ...others] = fruits;
console.log(first); // 'apple'
console.log(second); // 'banana'
console.log(others); // ['cherry', 'date']
Array Methods
JavaScript provides numerous methods to manipulate arrays.
concat():
Merges arrays
let combinedArrays = arrayOne.concat(arrayTwo);
filter():
Iterates over an array and filters to only a specified set of results. The
call back function
must return a test that evaluates to be true or false. If the callback function is advanced, define it outside
of the function. Filter will return an array. If you are seeking only 1 value, add [0] after filter() to return
one object or value instead of an array with 1 item.
// Syntax: const newArray = oldArray.filter(arrow function => conditional);
// Example for filtering by names starting with m
const newArray = names.filter(name => name.charAt[0] === "m");
indexOf(item, fromIndex):
Returns the first index of the item.
fruits.indexOf('apple');
lastIndexOf(item, fromIndex):
Returns the last index of the item.
fruits.lastIndexOf('apple');
length:
Returns the number of elements in the array.
console.log(fruits.length);
map():
Takes a callback function as the parameter and map() iterates over an array, applying this function, and
returns a new array of results.
const results = numbers.map(num => num *2);
pop():
Removes the last element.
fruits.pop();
push():
Adds one or more elements to the end.
fruits.push('elderberry');
reduce():
Reduces all elements of an array into a single output value.
// Syntax: arrayName.reduce((acc, curr) => );
// acc: accumulator
// curr: current
// Example (sum numbers in an array)
const sum = numbers.reduce((acc,curr) => acc + cur);
reverse():
Reverses the array.
fruits.reverse();
shift():
Removes the first element and shifts all element indexes one to the left.
fruits.shift();
slice(start, end):
Returns a shallow copy of a portion of an array.
let citrus = fruits.slice(1, 3);
sort():
Sorts the elements in various ways. By default it sorts alphabetically.
fruits.sort();
splice(start, deleteCount, item1, item2, ...):
Adds/removes elements.
fruits.splice(1, 0, 'grape'); // Inserts 'grape' at index 1
unshift():
Adds one or more elements to the beginning and shifts all other elements to the right.
fruits.unshift('fig');