JavaScript Arrays: Stop Writing For Loops
Modern JavaScript has powerful array methods that replace verbose for loops with expressive, chainable operations. Here's every method you'll actually use.
Transform: map()
const users = [{ name: 'Alice', age: 30 }, { name: 'Bob', age: 25 }];
const names = users.map(u => u.name);
// ['Alice', 'Bob']
const doubled = [1, 2, 3].map(n => n * 2);
// [2, 4, 6]Filter: filter()
const adults = users.filter(u => u.age >= 18);
const evens = [1, 2, 3, 4, 5].filter(n => n % 2 === 0);
// [2, 4]Reduce: reduce()
const total = [10, 20, 30].reduce((sum, n) => sum + n, 0);
// 60
// Group by
const items = [{ type: 'fruit', name: 'apple' }, { type: 'veg', name: 'carrot' }, { type: 'fruit', name: 'banana' }];
const grouped = items.reduce((acc, item) => {
(acc[item.type] ??= []).push(item.name);
return acc;
}, {});
// { fruit: ['apple', 'banana'], veg: ['carrot'] }
// Modern alternative: Object.groupBy (ES2024)
const grouped2 = Object.groupBy(items, item => item.type);Search: find(), findIndex(), includes()
const alice = users.find(u => u.name === 'Alice');
// { name: 'Alice', age: 30 }
const idx = users.findIndex(u => u.name === 'Bob');
// 1
[1, 2, 3].includes(2); // true
[1, 2, 3].indexOf(2); // 1 (or -1 if not found)Test: some(), every()
const hasAdmin = users.some(u => u.role === 'admin');
// true if ANY user is admin
const allAdults = users.every(u => u.age >= 18);
// true if ALL users are adultsFlatten: flat(), flatMap()
[[1, 2], [3, 4], [5]].flat();
// [1, 2, 3, 4, 5]
[[1, [2]], [3]].flat(Infinity);
// [1, 2, 3]
// flatMap = map + flat(1)
const sentences = ['hello world', 'foo bar'];
sentences.flatMap(s => s.split(' '));
// ['hello', 'world', 'foo', 'bar']Sort and Reverse
// sort() mutates! Use toSorted() for immutable
const sorted = [3, 1, 2].toSorted((a, b) => a - b);
// [1, 2, 3]
// Sort objects
users.toSorted((a, b) => a.age - b.age);
// Reverse (immutable)
const reversed = [1, 2, 3].toReversed();
// [3, 2, 1]New Methods (ES2023+)
// toSorted(), toReversed(), toSpliced() — immutable versions
const arr = [3, 1, 2];
arr.toSorted(); // [1, 2, 3] — arr unchanged
arr.toReversed(); // [2, 1, 3] — arr unchanged
// findLast(), findLastIndex()
[1, 2, 3, 2, 1].findLast(n => n === 2); // 2 (last one)
[1, 2, 3, 2, 1].findLastIndex(n => n === 2); // 3
// Array.from — create arrays from iterables
Array.from({ length: 5 }, (_, i) => i);
// [0, 1, 2, 3, 4]
Array.from('hello');
// ['h', 'e', 'l', 'l', 'o']Chaining
const result = users
.filter(u => u.age >= 18)
.map(u => u.name)
.toSorted();
// Filtered, transformed, sorted — no intermediate variablesFormat your code: JavaScript Formatter — paste code, get formatted output.