Array Creation and Basics
// Creating arrays
let arr1 = [1, 2, 3];
let arr2 = new Array(1, 2, 3);
let arr3 = Array.of(1, 2, 3);
let arr4 = Array(5).fill(0); // [0,0,0,0,0]
// Basic operations
arr.length // Get length
arr[0] // Access first element
arr[arr.length-1] // Access last element
arr.push(4) // Add to end
arr.pop() // Remove from end
arr.unshift(0) // Add to beginning
arr.shift() // Remove from beginning
Array creation and basic operations
Array Methods
// Iteration
arr.forEach(item => console.log(item));
arr.map(x => x * 2);
arr.filter(x => x > 2);
arr.find(x => x > 2);
arr.findIndex(x => x > 2);
arr.every(x => x > 0);
arr.some(x => x > 2);
// Transformation
arr.reduce((acc, curr) => acc + curr, 0);
arr.sort((a, b) => a - b);
arr.reverse();
arr.slice(1, 3); // Extract portion
arr.splice(1, 2); // Remove/add elements
// Search
arr.includes(2);
arr.indexOf(2);
arr.lastIndexOf(2);
Common array methods
ES6+ Array Methods
// Spread operator
let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
let combined = [...arr1, ...arr2];
// Destructuring
let [first, second, ...rest] = [1, 2, 3, 4, 5];
// Array.from()
let str = "hello";
let chars = Array.from(str); // ['h','e','l','l','o']
// find() and includes()
let users = [{id: 1, name: "John"}];
let user = users.find(u => u.id === 1);
let hasTwo = [1, 2, 3].includes(2);
Modern array features