Master JavaScript arrays - the fundamental data structure for storing collections. Learn to create, manipulate, and process arrays using powerful built-in methods like map, filter, reduce, and more.
Master JavaScript arrays - the fundamental data structure for storing collections. Learn to create, manipulate, and process arrays using powerful built-in methods like map, filter, reduce, and more.
Arrays store multiple values in a single variable, indexed starting from 0:
1// Array creation methods
2const fruits = ["apple", "banana", "orange"];
3const numbers = new Array(1, 2, 3, 4, 5);
4const mixed = ["text", 42, true, null];
5const empty = [];
6
7console.log(fruits[0]); // "apple" (first element)
8console.log(fruits[2]); // "orange" (third element)
9console.log(fruits.length); // 3 (number of elements)Essential array operations you'll use constantly:
1const colors = ["red", "green", "blue"];
2
3// Length property
4console.log(colors.length); // 3
5
6// Adding elements
7colors.push("yellow"); // Add to end
8colors.unshift("purple"); // Add to beginning
9console.log(colors); // ["purple", "red", "green", "blue", "yellow"]
10
11// Removing elements
12const last = colors.pop(); // Remove from end, returns "yellow"
13const first = colors.shift(); // Remove from beginning, returns "purple"
14console.log(colors); // ["red", "green", "blue"]
15
16// Modifying elements
17colors[1] = "lime"; // Change second element
18console.log(colors); // ["red", "lime", "blue"]Understanding how array indexing works:
1const items = ["first", "second", "third"];
2
3// Valid indices: 0, 1, 2
4console.log(items[0]); // "first"
5console.log(items[1]); // "second"
6console.log(items[2]); // "third"
7
8// Invalid indices return undefined
9console.log(items[3]); // undefined
10console.log(items[-1]); // undefined (not like Python!)
11
12// Dynamic length
13items[5] = "sixth"; // Creates sparse array
14console.log(items); // ["first", "second", "third", undefined, undefined, "sixth"]
15console.log(items.length); // 6Methods that modify the original array:
1const numbers = [1, 2, 3];
2
3// Adding elements
4numbers.push(4, 5); // Add multiple to end: [1, 2, 3, 4, 5]
5numbers.unshift(0); // Add to beginning: [0, 1, 2, 3, 4, 5]
6
7// Removing elements
8const last = numbers.pop(); // Remove last, returns 5
9const first = numbers.shift(); // Remove first, returns 0
10// Now: [1, 2, 3, 4]
11
12// Splice: remove/add at any position
13numbers.splice(1, 2, "two", "three"); // Remove 2 items at index 1, add replacements
14console.log(numbers); // [1, "two", "three", 4]Methods to locate elements in arrays:
1const animals = ["cat", "dog", "bird", "cat", "fish"];
2
3// indexOf: first occurrence index
4console.log(animals.indexOf("cat")); // 0
5console.log(animals.indexOf("rabbit")); // -1 (not found)
6
7// lastIndexOf: last occurrence index
8console.log(animals.lastIndexOf("cat")); // 3
9
10// includes: check if element exists
11console.log(animals.includes("dog")); // true
12console.log(animals.includes("rabbit")); // false
13
14// find: first element matching condition
15const longAnimal = animals.find(animal => animal.length > 3);
16console.log(longAnimal); // "bird"
17
18// findIndex: index of first match
19const longIndex = animals.findIndex(animal => animal.length > 3);
20console.log(longIndex); // 2Methods that create new arrays:
1const fruits = ["apple", "banana"];
2const vegetables = ["carrot", "broccoli"];
3
4// concat: combine arrays
5const food = fruits.concat(vegetables);
6console.log(food); // ["apple", "banana", "carrot", "broccoli"]
7
8// slice: extract portion (doesn't modify original)
9const someFruits = food.slice(0, 2); // Get first 2 elements
10console.log(someFruits); // ["apple", "banana"]
11console.log(food); // Original unchanged
12
13// join: create string from array
14const fruitString = fruits.join(" and ");
15console.log(fruitString); // "apple and banana"
16
17// split: create array from string (String method, but useful with arrays)
18const sentence = "hello,world,javascript";
19const words = sentence.split(",");
20console.log(words); // ["hello", "world", "javascript"]The forEach method runs a function for each array element:
1const names = ["Alice", "Bob", "Charlie"];
2
3// Basic forEach
4names.forEach(name => {
5 console.log("Hello, " + name);
6});
7
8// With index parameter
9names.forEach((name, index) => {
10 console.log(`${index + 1}. ${name}`);
11});
12
13// With array parameter (rarely used)
14names.forEach((name, index, array) => {
15 console.log(`${name} is ${index + 1} of ${array.length}`);
16});Map creates a new array by transforming each element:
1const numbers = [1, 2, 3, 4, 5];
2
3// Transform to squares
4const squares = numbers.map(num => num * num);
5console.log(squares); // [1, 4, 9, 16, 25]
6
7// Transform to strings
8const strings = numbers.map(num => "Number: " + num);
9console.log(strings); // ["Number: 1", "Number: 2", ...]
10
11// Transform objects
12const users = [
13 { name: "Alice", age: 25 },
14 { name: "Bob", age: 30 }
15];
16
17const userSummaries = users.map(user => ({
18 summary: `${user.name} is ${user.age} years old`,
19 isAdult: user.age >= 18
20}));
21console.log(userSummaries);Filter creates a new array with elements that pass a test:
1const ages = [16, 21, 18, 15, 25, 19];
2
3// Adults only
4const adults = ages.filter(age => age >= 18);
5console.log(adults); // [21, 18, 25, 19]
6
7// Even numbers
8const evenAges = ages.filter(age => age % 2 === 0);
9console.log(evenAges); // [16, 18]
10
11// Complex filtering
12const products = [
13 { name: "Laptop", price: 999, inStock: true },
14 { name: "Phone", price: 599, inStock: false },
15 { name: "Tablet", price: 399, inStock: true }
16];
17
18const availableProducts = products.filter(product =>
19 product.inStock && product.price < 800
20);
21console.log(availableProducts); // Only tablet matchesReduce is the most powerful array method - it combines all elements into a single value:
1const numbers = [1, 2, 3, 4, 5];
2
3// Sum all numbers
4const sum = numbers.reduce((total, current) => total + current, 0);
5console.log(sum); // 15
6
7// Find maximum
8const max = numbers.reduce((maximum, current) =>
9 current > maximum ? current : maximum, numbers[0]);
10console.log(max); // 5
11
12// Build an object
13const fruits = ["apple", "banana", "apple", "orange", "banana"];
14const count = fruits.reduce((acc, fruit) => {
15 acc[fruit] = (acc[fruit] || 0) + 1;
16 return acc;
17}, {});
18console.log(count); // { apple: 2, banana: 2, orange: 1 }Sort arranges elements in order (modifies original array):
1// String sorting (alphabetical)
2const fruits = ["banana", "apple", "cherry"];
3fruits.sort();
4console.log(fruits); // ["apple", "banana", "cherry"]
5
6// Number sorting (requires comparison function)
7const numbers = [10, 2, 30, 4];
8numbers.sort((a, b) => a - b); // Ascending
9console.log(numbers); // [2, 4, 10, 30]
10
11// Descending order
12numbers.sort((a, b) => b - a);
13console.log(numbers); // [30, 10, 4, 2]
14
15// Object sorting
16const people = [
17 { name: "Alice", age: 30 },
18 { name: "Bob", age: 25 },
19 { name: "Charlie", age: 35 }
20];
21
22people.sort((a, b) => a.age - b.age); // Sort by age
23console.log(people); // Bob(25), Alice(30), Charlie(35)Test conditions across array elements:
1const ages = [22, 25, 30, 19, 28];
2
3// every: all elements must pass test
4const allAdults = ages.every(age => age >= 18);
5console.log(allAdults); // true
6
7// some: at least one element must pass test
8const hasMinors = ages.some(age => age < 21);
9console.log(hasMinors); // true
10
11const products = [
12 { name: "Laptop", inStock: true, price: 999 },
13 { name: "Phone", inStock: false, price: 699 },
14 { name: "Tablet", inStock: true, price: 399 }
15];
16
17const allInStock = products.every(product => product.inStock);
18console.log(allInStock); // false
19
20const hasExpensive = products.some(product => product.price > 500);
21console.log(hasExpensive); // true1const numbers = [1, 2, 3, 4, 5];
2numbers.reverse(); // Modifies original
3console.log(numbers); // [5, 4, 3, 2, 1]
4
5// To avoid modifying original, use spread operator
6const original = [1, 2, 3, 4, 5];
7const reversed = [...original].reverse();
8console.log(original); // [1, 2, 3, 4, 5] (unchanged)
9console.log(reversed); // [5, 4, 3, 2, 1]Your progress is saved in this browser, on this device only.