Learn how to create and manipulate arrays in JavaScript with these simple examples.
1. Basic Array Operations
// Create and modify an array
let fruits = ['Apple', 'Banana'];
fruits.push('Orange'); // Add to end
fruits.unshift('Mango'); // Add to start
fruits.pop(); // Remove from end
fruits.shift(); // Remove from start
2. Array Methods (map, filter)
// Transform array items
let numbers = [1, 2, 3, 4, 5];
let doubled = numbers.map(n => n * 2);
let evens = numbers.filter(n => n % 2 === 0);
3. Finding Items
// Search in array
let colors = ['red', 'blue', 'green'];
let found = colors.find(c => c === 'blue');
let index = colors.indexOf('green');
4. Sorting and Joining
// Sort and join array items
let words = ['banana', 'apple', 'orange'];
words.sort(); // Alphabetical sort
let text = words.join(', ');
Array Methods and Syntax
Basic Array Methods
// Creating arrays
let array = ['item1', 'item2', 'item3'];
let numbers = [1, 2, 3, 4, 5];
// Adding elements
array.push('new item'); // Add to end
array.unshift('first item'); // Add to start
// Removing elements
array.pop(); // Remove from end
array.shift(); // Remove from start
// Finding elements
array.indexOf('item2'); // Get index
array.includes('item2'); // Check if exists
array.find(x => x === 'item2'); // Find with condition
Advanced Array Methods
// Transforming arrays
let doubled = numbers.map(x => x * 2);
let evens = numbers.filter(x => x % 2 === 0);
let sum = numbers.reduce((a, b) => a + b, 0);
// Sorting and reversing
array.sort(); // Sort alphabetically
array.reverse(); // Reverse order
// Other useful methods
array.slice(1, 3); // Get portion of array
array.join(', '); // Join into string
array.concat([4, 5]); // Combine arrays
Practice Exercises
Exercise 1: Shopping Cart
Create an array-based shopping cart with the following operations:
Add items to cart
Remove items from cart
Calculate total price
// Your solution here
let cart = [];
let prices = {
apple: 1,
banana: 0.5,
orange: 0.75
};
// Add item to cart
function addToCart(item) {
cart.push(item);
}
// Remove item from cart
function removeFromCart(item) {
const index = cart.indexOf(item);
if (index > -1) {
cart.splice(index, 1);
}
}
// Calculate total
function getTotal() {
return cart.reduce((total, item) => {
return total + prices[item];
}, 0);
}
Exercise 2: Array Transformation
Create functions that transform an array of numbers:
Double all numbers
Keep only even numbers
Calculate the sum
// Your solution here
const numbers = [1, 2, 3, 4, 5];
// Double all numbers
const doubled = numbers.map(x => x * 2);
// Keep even numbers
const evens = numbers.filter(x => x % 2 === 0);
// Calculate sum
const sum = numbers.reduce((a, b) => a + b, 0);