JavaScript: JavaScript Arrays Advanced
In the previous lesson, you learned basic array operations. Now let's level up with array "power moves" — higher-order methods. These let you do more with less code and are essential skills in modern JavaScript development.
1. map — Transform Each Element
map runs a function on every element and returns a new array — the original stays unchanged. Think of it as an assembly line: each element goes in, gets transformed, and comes out as part of a new product.
<!-- Script tag -->
<script>
let prices = [10, 20, 30];
let doubled = prices.map(p => p * 2); // [20, 40, 60]
</script>
The callback receives three arguments: (element, index, originalArray). Most of the time you only need the first one.
2. filter — Keep What Passes
filter keeps elements that pass a test and returns a new array — the original is untouched. Like a security checkpoint: items that meet the criteria go through; the rest get filtered out.
<!-- Script tag -->
<script>
let scores = [45, 80, 92, 55, 78, 98];
let passed = scores.filter(s => s >= 60); // [80, 92, 78, 98]
</script>
Elements where the callback returns true are kept; those returning false are discarded.
3. reduce — Accumulate Into One Value
reduce "compresses" an array into a single value. The most common use case is summing:
<!-- Script tag -->
<script>
let nums = [1, 2, 3, 4, 5];
let sum = nums.reduce((acc, cur) => acc + cur, 0); // 15
</script>
What the parameters mean:
acc(accumulator): the running total, carried over from the previous iterationcur(current): the current element- The second argument
0is the initial value for the accumulator
reduce seems tricky at first, but its essence is simple: step by step, compress the array into one value. Summing, finding the max, counting occurrences — reduce handles them all.
▶ Example: Combining map, filter, and reduce
▶ Try it Yourself4. find and findIndex
If nothing is found, find returns undefined and findIndex returns -1.
<!-- Script tag -->
<script>
let users = [
{ name: 'Alice', age: 20 },
{ name: 'Bob', age: 17 },
{ name: 'Charlie', age: 25 }
];
users.find(u => u.age > 22); // { name: 'Charlie', age: 25 }
users.findIndex(u => u.age < 18); // 1 (Bob's index)
</script>
5. sort — Order Elements
sort arranges the array in place (it modifies the original!). By default it sorts as strings, which trips up many beginners:
<!-- Script tag -->
<script>
let nums = [10, 1, 21, 2];
nums.sort(); // [1, 10, 2, 21] ← String sort! "10" < "2"
// Correct: numeric sort requires a comparator function
nums.sort((a, b) => a - b); // [1, 2, 10, 21] ← Ascending
nums.sort((a, b) => b - a); // [21, 10, 2, 1] ← Descending
</script>
sort mutates the original array! To keep the original intact, copy first: [...arr].sort(...).
▶ Example: Sorting Student Scores
▶ Try it Yourself6. some and every
some— does at least one element pass the test? (returns a boolean)every— do all elements pass the test? (returns a boolean)
<!-- Script tag -->
<script>
let scores = [60, 75, 82, 90];
scores.some(s => s >= 90); // true — someone scored 90+
scores.some(s => s === 100); // false — no one got a perfect score
scores.every(s => s >= 60); // true — everyone passed
</script>
some asks "is there anyone who...", while every asks "does everyone...". One checks for existence; the other checks for completeness.
7. Spread Operator (...)
The spread operator ... "unpacks" an array. It's commonly used for copying and merging:
<!-- Script tag -->
<script>
let a = [1, 2, 3];
let b = [...a]; // Copy: [1, 2, 3] (new array, not a reference)
let c = [...a, 4, 5]; // Merge: [1, 2, 3, 4, 5]
let d = [0, ...a, 4]; // Insert: [0, 1, 2, 3, 4]
let x = [1, 2], y = [3, 4];
let z = [...x, ...y]; // [1, 2, 3, 4]
</script>
8. Destructuring Assignment
Extract values from an array and assign them to variables by position:
<!-- Script tag -->
<script>
let [a, b, c] = [1, 2, 3];
// a = 1, b = 2, c = 3
let [first, ...rest] = [1, 2, 3, 4, 5];
// first = 1, rest = [2, 3, 4, 5]
let [name, score] = ['Alice', 95];
// name = 'Alice', score = 95
</script>
9. Chaining Methods
Higher-order methods return new arrays, so you can chain them one after another:
<!-- Script tag -->
<script>
let result = students
.filter(s => s.score >= 60) // First, filter passing students
.map(s => s.name) // Then, extract names
.sort(); // Finally, sort
</script>
▶ Example: Chaining to Process Data
▶ Try it Yourself▶ Example: Spread Operator and Destructuring
▶ Try it Yourself❓ FAQ
map returns a new array made of the callback's return values, while forEach only iterates and returns undefined. Use map when you need the processed result, and use forEach when you only want to perform side effects such as printing or sending requests. Don't manually push into an external array inside forEach—that is exactly what map is for.sort give wrong results for number arrays, e.g. [10, 2, 1].sort() returns [1, 10, 2]?sort converts elements to strings and compares them by UTF-16 code units, so 10 comes before 2. To sort numbers, pass a comparator: arr.sort((a, b) => a - b) for ascending and b - a for descending. Also, sort sorts in place and mutates the original array, so if you don't want that, do [...arr].sort(...) first.reduce to sum or group an array of objects by a certain field?0 and accumulate the field in the callback: arr.reduce((sum, item) => sum + item.price, 0). For grouping, set the initial value to {} and create keys by field and push in the callback. Always pass the initial value explicitly so it won't throw on an empty array.📖 Summary
maptransforms each element into a new array,filterkeeps matching elements,reduceaccumulates into a single valuefindreturns the first matching element,findIndexreturns the first matching indexsortdefaults to string ordering — for numbers, always pass a comparator:(a, b) => a - bsomechecks if any element matches,everychecks if all elements match- The spread operator
...copies and merges arrays; destructuring extracts elements into variables - Higher-order methods return new arrays and can be chained for concise, readable code
📝 Exercises
- Given the array
[3, 8, 12, 5, 9, 17, 4], usefilterto keep numbers greater than 7, thenmapto double them. Output the result. - Use
reduceto count occurrences of each word in an array like['apple', 'banana', 'apple', 'cherry', 'banana', 'apple']→{ apple: 3, banana: 2, cherry: 1 }. - Given an array of students (with
nameandscore), use chaining to: filter passing students → sort by score descending → extract names into a new array. Display the result on the page.