Arrays
Array Creation
const arr = [1, 2, 3];
const arr2 = new Array(1, 2, 3);
const arr3 = Array.from({ length: 3 }, (_, i) => i); // [0, 1, 2]
const arr4 = Array.of(1, 2, 3);
// Create array from string
const chars = Array.from('hello'); // ['h', 'e', 'l', 'l', 'o']
// Create array with specific length
const empty = new Array(5); // [undefined, undefined, undefined, undefined, undefined]
const filled = new Array(5).fill(0); // [0, 0, 0, 0, 0]
Array Methods
Mutating Methods (modify original array)
const numbers = [1, 2, 3, 4, 5];
// Add/remove elements
numbers.push(6); // Add to end → [1, 2, 3, 4, 5, 6]
numbers.pop(); // Remove from end → [1, 2, 3, 4, 5]
numbers.unshift(0); // Add to beginning → [0, 1, 2, 3, 4, 5]
numbers.shift(); // Remove from beginning → [1, 2, 3, 4, 5]
// Splice: remove/insert elements
numbers.splice(2, 1, 99); // Remove 1 at index 2, insert 99 → [1, 2, 99, 4, 5]
numbers.splice(1, 0, 1.5); // Insert 1.5 at index 1 → [1, 1.5, 2, 99, 4, 5]
// Sort and reverse
numbers.sort(); // Sort in place
numbers.reverse(); // Reverse in place
// Fill
numbers.fill(0, 2, 4); // Fill with 0 from index 2 to 4
Non-mutating Methods (return new array)
const numbers = [1, 2, 3, 4, 5];
// Extract portions
numbers.slice(1, 3); // Extract from index 1 to 3 → [2, 3]
numbers.slice(-2); // Last 2 elements → [4, 5]
// Combine arrays
numbers.concat([6, 7]); // Merge arrays → [1, 2, 3, 4, 5, 6, 7]
[...numbers, 6, 7]; // Spread syntax → [1, 2, 3, 4, 5, 6, 7]
// Convert to string
numbers.join('-'); // Convert to string → "1-2-3-4-5"
numbers.toString(); // → "1,2,3,4,5"
Iteration Methods
Basic Iteration
const numbers = [1, 2, 3, 4, 5];
// forEach: execute function for each element
numbers.forEach((num, index) => {
console.log(`${index}: ${num}`);
});
// For...of loop
for (const num of numbers) {
console.log(num);
}
// For...in loop (indices)
for (const index in numbers) {
console.log(`${index}: ${numbers[index]}`);
}
Transformation Methods
const numbers = [1, 2, 3, 4, 5];
// map: transform each element
const doubled = numbers.map(num => num * 2); // [2, 4, 6, 8, 10]
const withIndex = numbers.map((num, i) => `${i}: ${num}`); // ["0: 1", "1: 2", ...]
// flatMap: map then flatten
const nested = [1, 2, 3].flatMap(x => [x, x * 2]); // [1, 2, 2, 4, 3, 6]
Filtering & Testing
const numbers = [1, 2, 3, 4, 5, 6];
// filter: keep elements that pass test
const evens = numbers.filter(num => num % 2 === 0); // [2, 4, 6]
const greaterThan3 = numbers.filter(num => num > 3); // [4, 5, 6]
// find: first element that passes test
const firstEven = numbers.find(num => num % 2 === 0); // 2
const firstIndex = numbers.findIndex(num => num > 3); // 3 (index of 4)
// includes: check if element exists
numbers.includes(3); // true
numbers.includes(10); // false
// some: test if any element passes
numbers.some(num => num > 5); // true
numbers.some(num => num > 10); // false
// every: test if all elements pass
numbers.every(num => num > 0); // true
numbers.every(num => num > 3); // false
Reduce Methods
const numbers = [1, 2, 3, 4, 5];
// reduce: accumulate to single value
const sum = numbers.reduce((acc, num) => acc + num, 0); // 15
const product = numbers.reduce((acc, num) => acc * num, 1); // 120
const max = numbers.reduce((acc, num) => Math.max(acc, num)); // 5
// reduceRight: reduce from right to left
const rightJoin = numbers.reduceRight((acc, num) => acc + num, ''); // "54321"
// Complex reduce examples
const people = [
{ name: 'John', age: 30 },
{ name: 'Jane', age: 25 },
{ name: 'Bob', age: 35 },
];
// Group by age range
const grouped = people.reduce((acc, person) => {
const range = person.age < 30 ? 'young' : 'older';
acc[range] = acc[range] || [];
acc[range].push(person);
return acc;
}, {});
// Count occurrences
const fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple'];
const counts = fruits.reduce((acc, fruit) => {
acc[fruit] = (acc[fruit] || 0) + 1;
return acc;
}, {});
Array Destructuring
const [first, second, ...rest] = [1, 2, 3, 4, 5];
// first = 1, second = 2, rest = [3, 4, 5]
const [a, , c] = [1, 2, 3]; // Skip second element: a = 1, c = 3
const [x = 10, y = 20] = [1]; // Default values: x = 1, y = 20
// Swapping variables
let p = 1,
q = 2;
[p, q] = [q, p]; // p = 2, q = 1
// Nested destructuring
const nested = [
[1, 2],
[3, 4],
];
const [[a1, a2], [b1, b2]] = nested;
Advanced Array Operations
Array Flattening
// flat: flatten nested arrays
const nested = [1, [2, 3], [4, [5, 6]]];
nested.flat(); // [1, 2, 3, 4, [5, 6]]
nested.flat(2); // [1, 2, 3, 4, 5, 6] (depth 2)
nested.flat(Infinity); // Flatten all levels
Sorting
const numbers = [3, 1, 4, 1, 5, 9];
const strings = ['banana', 'apple', 'cherry'];
// Basic sorting
numbers.sort(); // [1, 1, 3, 4, 5, 9]
strings.sort(); // ["apple", "banana", "cherry"]
// Custom sorting
numbers.sort((a, b) => b - a); // Descending: [9, 5, 4, 3, 1, 1]
strings.sort((a, b) => a.length - b.length); // By length
// Sort objects
const people = [
{ name: 'John', age: 30 },
{ name: 'Jane', age: 25 },
{ name: 'Bob', age: 35 },
];
people.sort((a, b) => a.age - b.age); // Sort by age
people.sort((a, b) => a.name.localeCompare(b.name)); // Sort by name
Set Operations with Arrays
const arr1 = [1, 2, 3, 4];
const arr2 = [3, 4, 5, 6];
// Remove duplicates
const unique = [...new Set([1, 2, 2, 3, 3, 4])];
// Union
const union = [...new Set([...arr1, ...arr2])];
// Intersection
const intersection = arr1.filter(x => arr2.includes(x));
// Difference
const difference = arr1.filter(x => !arr2.includes(x));
Performance Considerations
// Use for...of for simple iteration (fastest)
for (const item of array) {
console.log(item);
}
// Use forEach for readability
array.forEach(item => console.log(item));
// Chain methods efficiently
const result = array
.filter(item => item.active)
.map(item => item.value)
.reduce((sum, value) => sum + value, 0);
// Avoid creating unnecessary intermediate arrays
// Good: single reduce
const avgOfActive = items.reduce(
(acc, item) => {
if (item.active) {
acc.sum += item.value;
acc.count++;
}
return acc;
},
{ sum: 0, count: 0 }
);
const average = avgOfActive.sum / avgOfActive.count;
// Less efficient: multiple iterations
const activeItems = items.filter(item => item.active);
const values = activeItems.map(item => item.value);
const sum = values.reduce((acc, val) => acc + val, 0);
const average2 = sum / values.length;