intro-frontend-course

Lecture 2: JavaScript Arrays

Introduction to JavaScript Arrays

Arrays are a special type of object in JavaScript used to store multiple values in a single variable. Arrays are ordered collections, meaning the items have a specific order, and they can hold different types of data, including numbers, strings, objects, and even other arrays.

Creating Arrays

There are several ways to create arrays in JavaScript:

  1. Array Literals

Real-World Example: A Shopping List

const shoppingList = ['Milk', 'Bread', 'Eggs', 'Butter'];
  1. Using the Array Constructor
const shoppingList = new Array('Milk', 'Bread', 'Eggs', 'Butter');

Accessing Array Elements

You can access elements in an array using their index, starting from 0.

console.log(shoppingList[0]); // Milk
console.log(shoppingList[2]); // Eggs

Modifying Array Elements

You can modify elements directly using their index.

shoppingList[1] = 'Bananas';
console.log(shoppingList); // ['Milk', 'Bananas', 'Eggs', 'Butter']

Array Methods

JavaScript provides numerous built-in methods for working with arrays. Here are some commonly used methods:

  1. push and pop

Real-World Example: Adding and Removing Items from a Cart

const cart = ['Laptop', 'Mouse', 'Keyboard'];
cart.push('Monitor'); // Add an item to the end
console.log(cart); // ['Laptop', 'Mouse', 'Keyboard', 'Monitor']

cart.pop(); // Remove the last item
console.log(cart); // ['Laptop', 'Mouse', 'Keyboard']
  1. shift and unshift
cart.unshift('Monitor'); // Add an item to the beginning
console.log(cart); // ['Monitor', 'Laptop', 'Mouse', 'Keyboard']

cart.shift(); // Remove the first item
console.log(cart); // ['Laptop', 'Mouse', 'Keyboard']
  1. splice

Real-World Example: Managing a Playlist

const playlist = ['Song1', 'Song2', 'Song3', 'Song4'];
playlist.splice(1, 2); // Remove 2 elements starting from index 1
console.log(playlist); // ['Song1', 'Song4']

playlist.splice(1, 0, 'NewSong'); // Add an element at index 1
console.log(playlist); // ['Song1', 'NewSong', 'Song4']
  1. slice
const subPlaylist = playlist.slice(1, 3); // Get a sub-array from index 1 to 3 (not inclusive)
console.log(subPlaylist); // ['NewSong', 'Song4']
  1. forEach

Real-World Example: Logging Each Item in an Inventory

const inventory = ['Apples', 'Oranges', 'Bananas'];
inventory.forEach(item => {
  console.log(item);
});
// Apples
// Oranges
// Bananas
  1. map
const prices = [10, 20, 30];
const discountedPrices = prices.map(price => price * 0.9);
console.log(discountedPrices); // [9, 18, 27]
  1. filter

Real-World Example: Filtering Products by Availability

const products = [
  { name: 'Laptop', available: true },
  { name: 'Phone', available: false },
  { name: 'Tablet', available: true }
];

const availableProducts = products.filter(product => product.available);
console.log(availableProducts); // [{ name: 'Laptop', available: true }, { name: 'Tablet', available: true }]
  1. reduce
const totalCost = prices.reduce((total, price) => total + price, 0);
console.log(totalCost); // 60

Combining Arrays

You can combine arrays using the concat method or the spread operator.

const moreItems = ['Cheese', 'Yogurt'];
const fullShoppingList = shoppingList.concat(moreItems);
console.log(fullShoppingList); // ['Milk', 'Bananas', 'Eggs', 'Butter', 'Cheese', 'Yogurt']

const fullShoppingList2 = [...shoppingList, ...moreItems];
console.log(fullShoppingList2); // ['Milk', 'Bananas', 'Eggs', 'Butter', 'Cheese', 'Yogurt']

Finding Elements

Use find and findIndex to locate elements in an array.

const foundItem = shoppingList.find(item => item === 'Eggs');
console.log(foundItem); // Eggs

const foundIndex = shoppingList.findIndex(item => item === 'Eggs');
console.log(foundIndex); // 2

Checking Array Contents

Use includes to check if an array contains a specific element.

const hasButter = shoppingList.includes('Butter');
console.log(hasButter); // true

Sorting and Reversing Arrays

Real-World Example: Sorting and Reversing a Leaderboard

const scores = [40, 100, 60, 80];
scores.sort((a, b) => b - a); // Sort in descending order
console.log(scores); // [100, 80, 60, 40]

scores.reverse(); // Reverse the order
console.log(scores); // [40, 60, 80, 100]

Practical Example: Managing a To-Do List

const todoList = [
  { task: 'Buy groceries', completed: false },
  { task: 'Clean the house', completed: true },
  { task: 'Pay bills', completed: false }
];

// Adding a new task
todoList.push({ task: 'Walk the dog', completed: false });

// Marking a task as completed
const taskIndex = todoList.findIndex(todo => todo.task === 'Buy groceries');
if (taskIndex !== -1) {
  todoList[taskIndex].completed = true;
}

// Removing a completed task
const updatedTodoList = todoList.filter(todo => !todo.completed);

console.log(updatedTodoList);

Video Resources:

By understanding and mastering JavaScript arrays, you can manage collections of data more effectively and perform complex operations with ease.