JavaScript: JavaScript Arrays Advanced

🗓 Last updated: 2026-11-30👤 Written by: Casey✓ Reviewed by: Dana🏷 Category: JavaScript Tutorial

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.

Related Array Methods:findIndex forEach filter reduce every find some sort map

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.

HTML
<!-- 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.

HTML
<!-- 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:

HTML
<!-- 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:

💡 Tip: 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 Yourself

4. find and findIndex

If nothing is found, find returns undefined and findIndex returns -1.

HTML
<!-- 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:

HTML
<!-- 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>
⚠️ Note: sort mutates the original array! To keep the original intact, copy first: [...arr].sort(...).

▶ Example: Sorting Student Scores

▶ Try it Yourself

6. some and every

HTML
<!-- 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>
💡 Tip: 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:

HTML
<!-- 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:

HTML
<!-- 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>
💡 Tip: Destructuring keeps code concise. When a function returns multiple values, wrapping them in an array and destructuring is a common pattern.


9. Chaining Methods

Higher-order methods return new arrays, so you can chain them one after another:

HTML
<!-- 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

Related Array Methods:findIndex forEach filter reduce every find some sort map

❓ FAQ

Q What exactly is the difference between map and forEach, and when should I use which?
A 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.
Q Why does sort give wrong results for number arrays, e.g. [10, 2, 1].sort() returns [1, 10, 2]?
A By default 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.
Q How do I use reduce to sum or group an array of objects by a certain field?
A For summing, set the initial value to 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

📝 Exercises

  1. Given the array [3, 8, 12, 5, 9, 17, 4], use filter to keep numbers greater than 7, then map to double them. Output the result.
  2. Use reduce to count occurrences of each word in an array like ['apple', 'banana', 'apple', 'cherry', 'banana', 'apple'] → { apple: 3, banana: 2, cherry: 1 }.
  3. Given an array of students (with name and score), use chaining to: filter passing students → sort by score descending → extract names into a new array. Display the result on the page.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏