Array Methods Deep Dive
Comprehensive guide to all array methods
Challenge
Section titled “Challenge”Master all array methods to transform, filter, and manipulate data efficiently without loops.
Explanation
Section titled “Explanation”Arrays are fundamental to JavaScript. Modern array methods provide functional programming capabilities for cleaner, more readable code.
Transformation Methods
Section titled “Transformation Methods”// map: Transform each elementconst numbers = [1, 2, 3, 4, 5];const doubled = numbers.map(n => n * 2);console.log(doubled); // [2, 4, 6, 8, 10]
// flatMap: Map and flatten one levelconst words = ['hello world', 'javascript rocks'];const letters = words.flatMap(word => word.split(''));console.log(letters); // ['h', 'e', 'l', 'l', 'o', ...]
// flat: Flatten nested arraysconst nested = [1, [2, 3], [4, [5, 6]]];console.log(nested.flat()); // [1, 2, 3, 4, [5, 6]]console.log(nested.flat(2)); // [1, 2, 3, 4, 5, 6]Filter and Search
Section titled “Filter and Search”// filter: Keep elements matching conditionconst numbers = [1, 2, 3, 4, 5];const even = numbers.filter(n => n % 2 === 0);console.log(even); // [2, 4]
// find: Get first matching elementconst found = numbers.find(n => n > 3);console.log(found); // 4
// findIndex: Get index of first matchconst index = numbers.findIndex(n => n > 3);console.log(index); // 3
// includes: Check if element existsconsole.log(numbers.includes(3)); // true
// some: Check if any element matchesconsole.log(numbers.some(n => n > 4)); // true
// every: Check if all elements matchconsole.log(numbers.every(n => n > 0)); // trueReduction Methods
Section titled “Reduction Methods”// reduce: Accumulate into single valueconst numbers = [1, 2, 3, 4, 5];
// Sumconst sum = numbers.reduce((acc, n) => acc + n, 0);console.log(sum); // 15
// Create object from arrayconst items = ['apple', 'banana', 'apple'];const counts = items.reduce((acc, item) => { acc[item] = (acc[item] || 0) + 1; return acc;}, {});console.log(counts); // { apple: 2, banana: 1 }
// reduceRight: Reduce from right to leftconst result = numbers.reduceRight((acc, n) => acc - n, 0);console.log(result); // -5Sorting and Ordering
Section titled “Sorting and Ordering”// sort: Mutates array!const numbers = [3, 1, 4, 1, 5];numbers.sort((a, b) => a - b);console.log(numbers); // [1, 1, 3, 4, 5]
// Non-mutating sortconst sorted = [...numbers].sort((a, b) => a - b);
// Complex sortingconst users = [ { name: 'John', age: 30 }, { name: 'Jane', age: 25 }, { name: 'Bob', age: 35 }];users.sort((a, b) => a.age - b.age);
// reverse: Also mutates!const reversed = [...numbers].reverse();Iteration Methods
Section titled “Iteration Methods”// forEach: Execute for each element (no return)const numbers = [1, 2, 3];numbers.forEach((n, index) => { console.log(`${index}: ${n}`);});
// Join and concatenateconst parts = ['Hello', 'World'];console.log(parts.join(' ')); // 'Hello World'
// concat: Combine arraysconst arr1 = [1, 2];const arr2 = [3, 4];const combined = arr1.concat(arr2); // [1, 2, 3, 4]const spread = [...arr1, ...arr2]; // [1, 2, 3, 4]Performance Considerations
Section titled “Performance Considerations”// ❌ Bad: Multiple iterationslet filtered = numbers.filter(n => n > 5);let mapped = filtered.map(n => n * 2);let result = mapped.reduce((a, b) => a + b, 0);
// ✅ Better: Single iterationlet result = numbers .filter(n => n > 5) .map(n => n * 2) .reduce((a, b) => a + b, 0);
// ✅ Best for large arrays: Custom reducelet result = numbers.reduce((acc, n) => { if (n > 5) { acc += n * 2; } return acc;}, 0);Practical Examples
Section titled “Practical Examples”// Group by propertyfunction groupBy(array, key) { return array.reduce((acc, item) => { const group = item[key]; if (!acc[group]) acc[group] = []; acc[group].push(item); return acc; }, {});}
// Unique elementsconst unique = (array) => [...new Set(array)];
// Partition arrayfunction partition(array, predicate) { return array.reduce( ([pass, fail], item) => predicate(item) ? [[...pass, item], fail] : [pass, [...fail, item]], [[], []] );}