Arrays
An array in JavaScript is a special data structure that allows you to store multiple values in a single variable. Arrays can hold numbers, strings, objects, or even other arrays.
What is an Array?
Think of an array as a list where you can store multiple items. Each item in the array is called an element, and it is stored in a specific position, called an index.
Example:
let fruits = ["Apple", "Banana", "Cherry"]; console.log(fruits); // Outputs: ["Apple", "Banana", "Cherry"]
Creating an Array
There are two main ways to create arrays in JavaScript:
a) Using Square Brackets (Recommended)
let numbers = [1, 2, 3, 4, 5];
b) Using the new Array() Constructor
let colors = new Array("Red", "Green", "Blue");
Accessing Elements in an Array
Array elements are accessed using their index. Indexes start at 0.
Example:
let animals = ["Dog", "Cat", "Elephant"]; console.log(animals[0]); // Outputs: Dog console.log(animals[2]); // Outputs: Elephant
If you try to access an index that doesn't exist, you'll get undefined.
Modifying Elements in an Array
You can change the value of an array element using its index.
Example:
let cars = ["Toyota", "Honda", "Ford"]; cars[1] = "BMW"; console.log(cars); // Outputs: ["Toyota", "BMW", "Ford"]
Array Properties and Length
length: The length property tells you how many elements are in the array.length: The length property tells you how many elements are in the array.
Example:
let cities = ["New York", "London", "Paris"]; console.log(cities.length); // Outputs: 3
Adding and Removing Elements
a) Adding Elements
- push(): Adds an element to the end of the array.
- unshift(): Adds an element to the beginning of the array.
Example:
let fruits = ["Apple", "Banana"]; fruits.push("Cherry"); // Adds to the end console.log(fruits); // Outputs: ["Apple", "Banana", "Cherry"] fruits.unshift("Mango"); // Adds to the beginning console.log(fruits); // Outputs: ["Mango", "Apple", "Banana", "Cherry"]
b) Removing Elements
- pop(): Removes the last element.
- shift(): Removes the first element.
Example:
fruits.pop(); // Removes "Cherry" console.log(fruits); // Outputs: ["Mango", "Apple", "Banana"] fruits.shift(); // Removes "Mango" console.log(fruits); // Outputs: ["Apple", "Banana"]
Looping Through an Array
You can use a loop to go through each element in an array.
a) Using a for Loop
let fruits = ["Apple", "Banana", "Cherry"]; for (let i = 0; i < fruits.length; i++) { console.log(fruits[i]); } // Outputs: // Apple // Banana // Cherry
b) Using for...of
for (let fruit of fruits) { console.log(fruit); } // Outputs: // Apple // Banana // Cherry
c) Using forEach()
fruits.forEach(function (fruit) { console.log(fruit); }); // Outputs: // Apple // Banana // Cherry
Common Array Methods
Here are some useful array methods:
Method | Description | Example |
---|---|---|
push() | Adds an element to the end | arr.push("New") |
pop() | Removes the last element | arr.pop() |
shift() | Removes the first element | arr.shift() |
unshift() | Adds an element to the beginning | arr.unshift("New") |
indexOf() | Returns the index of an element | arr.indexOf("Apple") |
includes() | Checks if an element exists in the array | arr.includes("Banana") |
slice() | Extracts a portion of the array | arr.slice(1, 3) |
splice() | Adds or removes elements from the array | arr.splice(1, 2, "New") |
join() | Combines all elements into a string | arr.join(", ") |
concat() | Combines two arrays | arr1.concat(arr2) |
reverse() | Reverses the array | arr.reverse() |
sort() | Sorts the array | arr.sort() |
Multi-dimensional Arrays
Arrays can contain other arrays, creating a table-like structure.
Example:
let matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]; console.log(matrix[0][1]); // Outputs: 2 (Row 0, Column 1) console.log(matrix[2][2]); // Outputs: 9 (Row 2, Column 2)
Example Program: Array Operations
Here's a program that demonstrates several array operations:
let numbers = [10, 20, 30, 40, 50]; // Add a number numbers.push(60); console.log(numbers); // Outputs: [10, 20, 30, 40, 50, 60] // Remove the first number numbers.shift(); console.log(numbers); // Outputs: [20, 30, 40, 50, 60] // Find the index of 40 let index = numbers.indexOf(40); console.log(index); // Outputs: 2 // Slice a portion of the array let sliced = numbers.slice(1, 4); console.log(sliced); // Outputs: [30, 40, 50]
The map() Method
The map() method is used to transform each element of an array and return a new array.
Syntax:
array.map(function (element, index, array) { // Return a transformed value });
Example: Double Each Number
let numbers = [1, 2, 3, 4]; let doubled = numbers.map(num => num * 2); console.log(doubled); // Outputs: [2, 4, 6, 8]
Key Points:
- Doesn’t change the original array.
- Always returns a new array.
The filter() Method
The filter() method is used to create a new array containing only the elements that pass a certain condition.
Syntax
array.filter(function (element, index, array) { // Return true to include the element });
Example: Filter Even Numbers
let numbers = [1, 2, 3, 4, 5, 6]; let evens = numbers.filter(num => num % 2 === 0); console.log(evens); // Outputs: [2, 4, 6]
Key Points:
- Doesn't change the original array.
- Returns a new array with elements that satisfy the condition.
The reduce() Method
The reduce() method is used to accumulate all elements of an array into a single value (e.g., sum, product, etc.).
Syntax:
array.reduce(function (accumulator, element, index, array) { // Combine the accumulator with the current element return newAccumulator; }, initialValue);
Example: Sum of Numbers
let numbers = [1, 2, 3, 4]; let sum = numbers.reduce((acc, num) => acc + num, 0); console.log(sum); // Outputs: 10
Key Points:
- Useful for calculations and combining data.
- Returns a single value.
The Spread Operator (...)
The spread operator allows you to expand elements of an array or object. It's written as three dots (...).
a) Copying Arrays
let fruits = ["Apple", "Banana"]; let moreFruits = [...fruits, "Cherry", "Mango"]; console.log(moreFruits); // Outputs: ["Apple", "Banana", "Cherry", "Mango"]
b) Combining Arrays
let arr1 = [1, 2]; let arr2 = [3, 4]; let combined = [...arr1, ...arr2]; console.log(combined); // Outputs: [1, 2, 3, 4]
c) Spread in Objects
let user = { name: "Alice", age: 25 }; let updatedUser = { ...user, city: "New York" }; console.log(updatedUser); // Outputs: { name: "Alice", age: 25, city: "New York" }
Destructuring Arrays
Destructuring makes it easy to unpack values from arrays or objects into variables.
a) Destructuring Arrays
let colors = ["Red", "Green", "Blue"]; let [first, second, third] = colors; console.log(first); // Outputs: Red console.log(second); // Outputs: Green console.log(third); // Outputs: Blue
b) Skipping Elements
let numbers = [10, 20, 30]; let [, second] = numbers; console.log(second); // Outputs: 20
c) Default Values
let items = ["Pen"]; let [item1, item2 = "Notebook"] = items; console.log(item1); // Outputs: Pen console.log(item2); // Outputs: Notebook
Combining Spread and Destructuring
You can use the spread operator with destructuring to get remaining items.
let fruits = ["Apple", "Banana", "Cherry", "Mango"]; let [first, second, ...rest] = fruits; console.log(first); // Outputs: Apple console.log(second); // Outputs: Banana console.log(rest); // Outputs: ["Cherry", "Mango"]
Real-World Example: Using map(), filter(), and reduce() Together
Example: Calculate the Total Price of Items Over $20
let products = [ { name: "Shirt", price: 15 }, { name: "Shoes", price: 50 }, { name: "Bag", price: 30 } ]; // Step 1: Filter items costing more than $20 let expensiveItems = products.filter(item => item.price > 20); // Step 2: Extract prices of those items let prices = expensiveItems.map(item => item.price); // Step 3: Calculate the total price let total = prices.reduce((acc, price) => acc + price, 0); console.log(total); // Outputs: 80