Arrays

Arrays are a special type of object in JavaScript used to store multiple values in a single variable. They are particularly useful for handling lists of items, such as numbers, strings, or even other arrays. Understanding arrays is fundamental for efficient data manipulation and storage in JavaScript.

1. Creating and Accessing Arrays

An array is created using square brackets [] and can contain multiple elements separated by commas.

Example:

let fruits = ["apple", "banana", "cherry"];
console.log(fruits); // ["apple", "banana", "cherry"]

You can access elements in an array by their index, with the first element having an index of 0.

Example:

console.log(fruits[0]); // "apple"
console.log(fruits[1]); // "banana"
console.log(fruits[2]); // "cherry"

2. Modifying Arrays

You can change the value of an array element by referencing its index.

Example:

fruits[1] = "blueberry";
console.log(fruits); // ["apple", "blueberry", "cherry"]

You can also add new elements to an array.

Example:

fruits[3] = "orange";
console.log(fruits); // ["apple", "blueberry", "cherry", "orange"]

3. Array Properties and Methods

Arrays come with several built-in properties and methods to help manage and manipulate the data they contain.

  • length: This property returns the number of elements in an array.

Example:

console.log(fruits.length); // 4
  • push(): Adds one or more elements to the end of an array and returns the new length of the array.

Example:

fruits.push("kiwi");
console.log(fruits); // ["apple", "blueberry", "cherry", "orange", "kiwi"]
  • pop(): Removes the last element from an array and returns that element.

Example:

let lastFruit = fruits.pop();
console.log(lastFruit); // "kiwi"
console.log(fruits); // ["apple", "blueberry", "cherry", "orange"]
  • unshift(): Adds one or more elements to the beginning of an array and returns the new length of the array.

Example:

fruits.unshift("strawberry");
console.log(fruits); // ["strawberry", "apple", "blueberry", "cherry", "orange"]
  • shift(): Removes the first element from an array and returns that element.

Example:

let firstFruit = fruits.shift();
console.log(firstFruit); // "strawberry"
console.log(fruits); // ["apple", "blueberry", "cherry", "orange"]
  • indexOf(): Returns the first index at which a given element can be found in the array, or -1 if it is not present.

Example:

let index = fruits.indexOf("cherry");
console.log(index); // 2
  • splice(): Adds and/or removes elements from an array.

Example:

fruits.splice(1, 2, "blackberry", "mango"); // Removes 2 elements at index 1 and adds "blackberry" and "mango"
console.log(fruits); // ["apple", "blackberry", "mango", "orange"]

4. Iterating Over Arrays

You can use loops to iterate over array elements. The for loop is commonly used for this purpose.

Example:

for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}
// Output:
// "apple"
// "blackberry"
// "mango"
// "orange"

You can also use the for...of loop to iterate over array elements more succinctly.

Example:

for (let fruit of fruits) {
  console.log(fruit);
}
// Output:
// "apple"
// "blackberry"
// "mango"
// "orange"

5. Map, Filter, and Reduce

Map, filter, and reduce are powerful array methods in JavaScript that allow you to perform common data manipulation tasks in a more declarative and readable way. Understanding how to use these methods can greatly enhance your ability to work with arrays and functional programming concepts.

5.1. The map Method

The map method creates a new array by applying a function to each element of an existing array. It does not modify the original array.

Syntax:

array.map(function(element, index, array) {
  // return new value for each element
});

Example:

const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8, 10]

In this example, the map method takes a function that multiplies each number by 2, and returns a new array with the doubled values.

Use Case: Creating a new array of objects based on an existing array of objects, such as formatting data for display.

const users = [
  { firstName: "Alice", lastName: "Johnson" },
  { firstName: "Bob", lastName: "Smith" }
];
const fullNames = users.map(user => `${user.firstName} ${user.lastName}`);
console.log(fullNames); // ["Alice Johnson", "Bob Smith"]

5.2. The filter Method

The filter method creates a new array with all elements that pass a test implemented by the provided function. It does not modify the original array.

Syntax:

array.filter(function(element, index, array) {
  // return true to keep the element, false otherwise
});

Example:

const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // [2, 4]

In this example, the filter method takes a function that returns true for even numbers, and returns a new array with only the even numbers.

Use Case: Filtering an array of objects based on a specific condition, such as getting all active users.

const users = [
  { name: "Alice", active: true },
  { name: "Bob", active: false },
  { name: "Charlie", active: true }
];
const activeUsers = users.filter(user => user.active);
console.log(activeUsers); // [{ name: "Alice", active: true }, { name: "Charlie", active: true }]

5.3. The reduce Method

The reduce method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value. It can be used for operations such as summing values, concatenating strings, or flattening arrays.

Syntax:

array.reduce(function(accumulator, element, index, array) {
  // return the new accumulator value
}, initialValue);

Example:

const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((total, num) => total + num, 0);
console.log(sum); // 15

In this example, the reduce method sums all the numbers in the array, starting with an initial value of 0.

Use Case: Calculating the total value of orders in an e-commerce application.

const orders = [
  { item: "Shoes", price: 50 },
  { item: "Hat", price: 20 },
  { item: "Shirt", price: 30 }
];
const totalPrice = orders.reduce((total, order) => total + order.price, 0);
console.log(totalPrice); // 100

Combining map, filter, and reduce

These methods can be combined to perform more complex data manipulations in a concise and readable way.

Example: Given an array of transactions, calculate the total amount of withdrawals.

const transactions = [
  { type: "deposit", amount: 100 },
  { type: "withdrawal", amount: 50 },
  { type: "withdrawal", amount: 30 },
  { type: "deposit", amount: 200 }
];

const totalWithdrawals = transactions
  .filter(transaction => transaction.type === "withdrawal")
  .map(transaction => transaction.amount)
  .reduce((total, amount) => total + amount, 0);

console.log(totalWithdrawals); // 80

In this example:

  • filter is used to select only the withdrawal transactions.

  • map is used to create an array of withdrawal amounts.

  • reduce is used to sum the withdrawal amounts.

Summary:

  • map: Transforms each element in an array and returns a new array.

  • filter: Filters elements in an array based on a condition and returns a new array.

  • reduce: Reduces an array to a single value using an accumulator function.

Understanding and using map, filter, and reduce effectively can greatly enhance your ability to manipulate arrays in JavaScript, leading to more concise and readable code.

6. Multi-dimensional Arrays

JavaScript allows you to create arrays of arrays, which are called multi-dimensional arrays. These are useful for representing complex data structures like matrices.

Example:

let matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

console.log(matrix[0][0]); // 1
console.log(matrix[1][1]); // 5
console.log(matrix[2][2]); // 9

Use Case:

Suppose you're building a simple application to manage a shopping list. You might use an array to store the list of items.

Example:

let shoppingList = ["milk", "bread", "eggs"];

// Add an item to the list
shoppingList.push("butter");
console.log(shoppingList); // ["milk", "bread", "eggs", "butter"]

// Remove the last item from the list
let lastItem = shoppingList.pop();
console.log(lastItem); // "butter"
console.log(shoppingList); // ["milk", "bread", "eggs"]

// Find the index of an item
let index = shoppingList.indexOf("bread");
console.log(index); // 1

// Remove an item by index
shoppingList.splice(index, 1);
console.log(shoppingList); // ["milk", "eggs"]

In this example:

  • We declare an array shoppingList to store the list of items.

  • We use push() to add an item to the list.

  • We use pop() to remove the last item from the list.

  • We use indexOf() to find the index of an item.

  • We use splice() to remove an item by its index.

This use case demonstrates how arrays can be used to manage lists of data. Understanding arrays is essential for working with collections of data in JavaScript. As you progress, you'll learn more advanced methods and techniques for manipulating arrays and other data structures.


Help us improve the content 🤩

You can leave comments here.

Last updated