# JavaScript Arrays Cheat Sheet ## Creating Arrays ```javascript // Array literal let arr = [1, 2, 3, 4, 5]; // Array constructor let arr2 = new Array(5); // Creates array with 5 empty slots let arr3 = new Array(1, 2, 3); // Creates [1, 2, 3] // Array.of() - creates array from arguments let arr4 = Array.of(7); // [7] (not array with 7 empty slots) // Array.from() - creates array from iterable let arr5 = Array.from("hello"); // ["h", "e", "l", "l", "o"] let arr6 = Array.from([1, 2, 3], x => x * 2); // [2, 4, 6] // Spread operator let original = [1, 2, 3]; let copy = [...original]; // Creates shallow copy let combined = [...original, 4, 5]; // [1, 2, 3, 4, 5] ``` ## Accessing Elements ```javascript let arr = [10, 20, 30, 40, 50]; arr[0]; // 10 (first element) arr[2]; // 30 arr[-1]; // undefined (negative indices don't work) arr.at(0); // 10 (ES2022) arr.at(-1); // 50 (last element, ES2022) arr.at(-2); // 40 (second to last) arr.length; // 5 ``` ## Adding & Removing Elements ```javascript let arr = [1, 2, 3]; // Add to end arr.push(4); // [1, 2, 3, 4], returns 4 (new length) arr.push(5, 6); // [1, 2, 3, 4, 5, 6] // Remove from end arr.pop(); // Returns 6, arr is [1, 2, 3, 4, 5] // Add to beginning arr.unshift(0); // [0, 1, 2, 3, 4, 5], returns 6 (new length) // Remove from beginning arr.shift(); // Returns 0, arr is [1, 2, 3, 4, 5] // Add/remove at specific position (splice) arr.splice(2, 0, 99); // At index 2, delete 0, add 99 // [1, 2, 99, 3, 4, 5] arr.splice(2, 1); // At index 2, delete 1 element // [1, 2, 3, 4, 5] arr.splice(2, 2, 'a', 'b'); // At index 2, delete 2, add 'a', 'b' // [1, 2, 'a', 'b', 5] ``` ## Iteration Methods ```javascript let arr = [1, 2, 3, 4, 5]; // forEach - execute function for each element arr.forEach((item, index, array) => { console.log(item, index); }); // for...of - iterate over values for (let value of arr) { console.log(value); } // for...in - iterate over indices (not recommended for arrays) for (let index in arr) { console.log(index); // "0", "1", "2", "3", "4" (strings!) } // Traditional for loop for (let i = 0; i < arr.length; i++) { console.log(arr[i]); } ``` ## Searching & Finding ```javascript let arr = [10, 20, 30, 40, 50, 30]; // indexOf - first index of element arr.indexOf(30); // 2 arr.indexOf(99); // -1 (not found) arr.indexOf(30, 3); // 5 (search from index 3) // lastIndexOf - last index of element arr.lastIndexOf(30); // 5 // includes - check if element exists arr.includes(30); // true arr.includes(99); // false // find - first element that passes test arr.find(x => x > 25); // 30 // findIndex - index of first element that passes test arr.findIndex(x => x > 25); // 2 // findLast - last element that passes test (ES2023) arr.findLast(x => x > 25); // 50 // findLastIndex - index of last element that passes test (ES2023) arr.findLastIndex(x => x > 25); // 4 // some - test if any element passes arr.some(x => x > 40); // true // every - test if all elements pass arr.every(x => x > 0); // true arr.every(x => x > 40); // false ``` ## Transforming Arrays ```javascript let arr = [1, 2, 3, 4, 5]; // map - create new array with transformed elements let doubled = arr.map(x => x * 2); // [2, 4, 6, 8, 10] let objects = arr.map((x, i) => ({ value: x, index: i })); // filter - create new array with elements that pass test let evens = arr.filter(x => x % 2 === 0); // [2, 4] // reduce - reduce array to single value let sum = arr.reduce((acc, x) => acc + x, 0); // 15 let product = arr.reduce((acc, x) => acc * x, 1); // 120 // reduce example: count occurrences let fruits = ["apple", "banana", "apple", "orange", "banana", "apple"]; let count = fruits.reduce((acc, fruit) => { acc[fruit] = (acc[fruit] || 0) + 1; return acc; }, {}); // { apple: 3, banana: 2, orange: 1 } // reduceRight - reduce from right to left let arr2 = [[0, 1], [2, 3], [4, 5]]; let flattened = arr2.reduceRight((acc, x) => acc.concat(x), []); // [4, 5, 2, 3, 0, 1] // flatMap - map then flatten one level let arr3 = [1, 2, 3]; arr3.flatMap(x => [x, x * 2]); // [1, 2, 2, 4, 3, 6] ``` ## Sorting & Reversing ```javascript let arr = [3, 1, 4, 1, 5, 9, 2]; // sort - sorts in place (modifies original) arr.sort(); // [1, 1, 2, 3, 4, 5, 9] // Sort numbers correctly (default sorts as strings) arr.sort((a, b) => a - b); // Ascending arr.sort((a, b) => b - a); // Descending // Sort objects let people = [ { name: "Charlie", age: 30 }, { name: "Alice", 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 // toSorted - creates new sorted array (ES2023) let original = [3, 1, 4]; let sorted = original.toSorted((a, b) => a - b); // original: [3, 1, 4], sorted: [1, 3, 4] // reverse - reverses in place arr.reverse(); // [9, 5, 4, 3, 2, 1, 1] // toReversed - creates new reversed array (ES2023) let reversed = original.toReversed(); ``` ## Combining & Slicing ```javascript let arr1 = [1, 2, 3]; let arr2 = [4, 5, 6]; // concat - combine arrays (returns new array) let combined = arr1.concat(arr2); // [1, 2, 3, 4, 5, 6] let multi = arr1.concat(arr2, [7, 8]); // [1, 2, 3, 4, 5, 6, 7, 8] // Spread operator (modern alternative) let combined2 = [...arr1, ...arr2]; // [1, 2, 3, 4, 5, 6] // slice - extract portion (doesn't modify original) let arr = [1, 2, 3, 4, 5]; arr.slice(2); // [3, 4, 5] (from index 2 to end) arr.slice(1, 4); // [2, 3, 4] (from index 1 to 4, not including 4) arr.slice(-2); // [4, 5] (last 2 elements) arr.slice(); // [1, 2, 3, 4, 5] (shallow copy) // join - convert to string arr.join(); // "1,2,3,4,5" arr.join(" - "); // "1 - 2 - 3 - 4 - 5" arr.join(""); // "12345" ``` ## Flattening Arrays ```javascript // flat - flatten nested arrays let nested = [1, [2, 3], [4, [5, 6]]]; nested.flat(); // [1, 2, 3, 4, [5, 6]] (1 level deep) nested.flat(2); // [1, 2, 3, 4, 5, 6] (2 levels deep) nested.flat(Infinity); // Flatten all levels // flatMap - map then flatten one level let arr = [1, 2, 3]; arr.flatMap(x => [x, x * 2]); // [1, 2, 2, 4, 3, 6] ``` ## Copying Arrays ```javascript let original = [1, 2, 3, {a: 4}]; // Shallow copies (nested objects/arrays still referenced) let copy1 = original.slice(); let copy2 = [...original]; let copy3 = Array.from(original); let copy4 = original.concat(); // Modifying nested object affects all shallow copies copy1[3].a = 99; console.log(original[3].a); // 99 // Deep copy (simple approach for JSON-compatible data) let deepCopy = JSON.parse(JSON.stringify(original)); // Modern deep copy (ES2023) let deepCopy2 = structuredClone(original); ``` ## Checking & Testing ```javascript // Array.isArray - check if value is an array Array.isArray([]); // true Array.isArray({}); // false Array.isArray("hello"); // false // length property let arr = [1, 2, 3, 4, 5]; arr.length; // 5 // Setting length truncates array arr.length = 3; // [1, 2, 3] arr.length = 5; // [1, 2, 3, empty × 2] ``` ## Filling & Creating Ranges ```javascript // fill - fill with static value let arr = [1, 2, 3, 4, 5]; arr.fill(0); // [0, 0, 0, 0, 0] arr.fill(7, 2, 4); // [0, 0, 7, 7, 0] (fill from index 2 to 4) // with - create new array with element replaced (ES2023) let arr2 = [1, 2, 3, 4, 5]; let updated = arr2.with(2, 99); // [1, 2, 99, 4, 5] // arr2 unchanged: [1, 2, 3, 4, 5] // Create range of numbers let range = Array.from({ length: 5 }, (_, i) => i); // [0, 1, 2, 3, 4] let range2 = Array.from({ length: 5 }, (_, i) => i + 1); // [1, 2, 3, 4, 5] let range3 = [...Array(5).keys()]; // [0, 1, 2, 3, 4] ``` ## Common Patterns ```javascript // Remove duplicates let arr = [1, 2, 2, 3, 4, 4, 5]; let unique = [...new Set(arr)]; // [1, 2, 3, 4, 5] // Shuffle array function shuffle(array) { let shuffled = [...array]; for (let i = shuffled.length - 1; i > 0; i--) { let j = Math.floor(Math.random() * (i + 1)); [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]]; } return shuffled; } // Chunk array function chunk(array, size) { return Array.from({ length: Math.ceil(array.length / size) }, (_, i) => array.slice(i * size, i * size + size) ); } chunk([1, 2, 3, 4, 5, 6, 7], 3); // [[1, 2, 3], [4, 5, 6], [7]] // Intersection of two arrays let arr1 = [1, 2, 3, 4]; let arr2 = [3, 4, 5, 6]; let intersection = arr1.filter(x => arr2.includes(x)); // [3, 4] // Difference between arrays let difference = arr1.filter(x => !arr2.includes(x)); // [1, 2] // Group by property let items = [ { category: "fruit", name: "apple" }, { category: "vegetable", name: "carrot" }, { category: "fruit", name: "banana" } ]; let grouped = items.reduce((acc, item) => { (acc[item.category] = acc[item.category] || []).push(item); return acc; }, {}); // { fruit: [{...}, {...}], vegetable: [{...}] } // Sum of array let numbers = [1, 2, 3, 4, 5]; let sum = numbers.reduce((a, b) => a + b, 0); // 15 // Maximum/minimum value let max = Math.max(...numbers); // 5 let min = Math.min(...numbers); // 1 // Average let avg = numbers.reduce((a, b) => a + b, 0) / numbers.length; // 3 // Flatten object array to single object let data = [{ a: 1 }, { b: 2 }, { c: 3 }]; let merged = Object.assign({}, ...data); // { a: 1, b: 2, c: 3 } ``` ## Multi-dimensional Arrays ```javascript // Create 2D array let matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]; // Access elements matrix[0][0]; // 1 matrix[1][2]; // 6 // Create empty 2D array let rows = 3, cols = 4; let grid = Array.from({ length: rows }, () => Array(cols).fill(0)); // Iterate 2D array for (let i = 0; i < matrix.length; i++) { for (let j = 0; j < matrix[i].length; j++) { console.log(matrix[i][j]); } } // Flatten 2D array let flattened = matrix.flat(); // [1, 2, 3, 4, 5, 6, 7, 8, 9] ```