Skip to main content

JavaScript Arrays and Array Methods

By SamK
0
0 recommends
Category(s)
Topic(s)

In this tutorial, you'll learn about arrays and array methods in JavaScript.

An array in JavaScript is a special type of object that allows you to store multiple values in a single variable. Each value in the array is called an element, and elements are indexed starting at 0.

Creating an Array

The simplest way to create a JavaScript array is by using an array literal.

Syntax:

let arrayName = [element1, element2, ...];

Example:

let fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits);
// Output: Array(3) [ "Apple", "Banana", "Cherry" ]

Using let allows reassignment, while const ensures the array reference remains unchanged.

Example:

const fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits); 
// Output: Array(3) [ "Apple", "Banana", "Cherry" ]

Using the JavaScript new Keyword

Another way to create an array:

const fruits = new Array("Apple", "Banana", "Cherry");
console.log(fruits); 
// Output: Array(3) [ "Apple", "Banana", "Cherry" ]

Accessing Array Elements

Retrieve an element using its index:

const fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits[0]); // Output: Apple

Last element:

const fruits = ["Banana", "Orange", "Apple", "Mango"];
console.log(fruits[fruits.length - 1]); // Output: Mango

Changing an Array Element

Modify a specific index:

const colors = ["Red", "Green", "Blue"];
colors[1] = "Yellow";
console.log(colors); 
// Output: Array(3) [ "Red", "Yellow", "Blue" ]

Converting an Array to a String

Use toString() to convert an array into a string:

const fruits = ["Apple", "Banana", "Cherry"];
let result = fruits.toString();
console.log(result); 
// String output: "Apple,Banana,Cherry"

The join() method allows specifying a separator:

console.log(fruits.join(" - ")); 
// String output: Banana - Orange - Apple - Mango

Arrays are Objects

Arrays in JavaScript are objects:

console.log(typeof []); // Output: object

Arrays use numeric indices, while objects use named properties:

const person = { firstName: "Robbin", lastName: "Zoo", age: 56 };
console.log(person.firstName); // Output: Robbin

Array Elements can be Objects

Arrays can hold objects:

const people = [
 { name: "Robbin", age: 30 },
 { name: "Jane", age: 25 },
 { name: "Doe", age: 35 }
];
console.log(people[0].name); // Output: Robbin
console.log(people[1].age);  // Output: 25

Array Properties and Methods

.length: Get the number of elements:

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

.sort(): Sort elements in ascending order:

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

Looping Through an Array

Using for loop:

const fruits = ["Cherry", "Mango", "Orange"];
for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}
// Output: 
Cherry
Mango
Orange

Using forEach():

fruits.forEach(fruit => console.log(fruit));
// Output: 
Cherry
Mango
Orange

Adding Elements to an Array

Using push():

const fruits = ["Apple", "Banana", "Cherry"];
fruits.push("Mango");
console.log(fruits); 
// Output: ["Apple", "Banana", "Cherry", "Mango"]

Using length property:

const fruits = ["Apple", "Banana", "Cherry"];
fruits[fruits.length] = "Mango";
console.log(fruits);
// Output: ["Apple", "Banana", "Cherry", "Mango"]

Using unshift() Method:

const fruits = ["Apple", "Banana", "Cherry"];
fruits.unshift("Lemon");
console.log(fruits); // Output: ["Lemon", "Apple", "Banana", "Cherry"]

Removing Elements to an Array

Using splice() method:

The splice(1, 1) method removes 1 element at index 1 ("Banana") from the array, leaving ["Apple", "Cherry"].

const fruits = ["Apple", "Banana", "Cherry"];
fruits.splice(1, 1);
console.log(fruits); // Output: ["Apple", "Cherry"]

Using slice() method:

The slice(1, 3) method extracts elements from index 1 to 2, returning ["Banana", "Cherry"] without modifying the original array.

const fruits = ["Apple", "Banana", "Cherry"];
const slicedFruits = fruits.slice(1, 3);
console.log(slicedFruits); // Output: ["Banana", "Cherry"]

Using pop() method:

The pop() method removes and returns the last element ("Cherry") from the array, modifying the original array.

const fruits = ["Apple", "Banana", "Cherry"];
const removedFruit = fruits.pop();
console.log(removedFruit); // Output: Cherry
console.log(fruits); // Output: ["Apple", "Banana"]

Using shift() method:

The shift() method removes and returns the first element ("Apple") from the array, modifying the original array.

const fruits = ["Apple", "Banana", "Cherry"];
const firstFruit = fruits.shift();
console.log(firstFruit); // Output: Apple
console.log(fruits); // Output: ["Banana", "Cherry"]

Recognizing an Array

Use Array.isArray() to check if a variable is an array:

const fruits = ["Apple", "Banana", "Cherry"];
console.log(Array.isArray(fruits)); // Output: true
const person = { firstName: "John", lastName: "Doe" };
console.log(Array.isArray(person)); // Output: false

Merging Arrays

concat() Method

const girls = ["Cecilie", "Lone"];
const boys = ["Emil", "Tobias", "Linus"];
const children = girls.concat(boys);
console.log(children); // Output: ["Cecilie", "Lone", "Emil", "Tobias", "Linus"]

Copying Elements

copyWithin() Method

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

Flattening Arrays

flat() Method

const nestedArray = [[1, 2], [3, 4], [5, 6]];
console.log(nestedArray.flat()); // Output: [1, 2, 3, 4, 5, 6]

flatMap() Method

const numbers = [1, 2, 3];
console.log(numbers.flatMap(n => [n, n * 10])); // Output: [1, 10, 2, 20, 3, 30]

Questions & Answers