JavaScript•Arrays
JavaScript Arrays: Methods (map, filter, reduce, slice)
Arrays are ordered, indexed lists in JavaScript supporting functional programming transformations.
Syntax
const arr = [1, 2, 3];
arr.push(4);
const mapped = arr.map(x => x * 2);
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| map() | Array Method | Creates a new array with results of calling a function on every item. |
| filter() | Array Method | Creates a new array with elements that pass the test function. |
| reduce() | Array Method | Reduces array to a single accumulator value. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing JavaScript locally:
// Modern Functional Array Operations
const cart = [
{ item: "Mechanical Keyboard", price: 120, inStock: true },
{ item: "Wireless Mouse", price: 45, inStock: true },
{ item: "USB Hub", price: 25, inStock: false },
{ item: "4K Monitor", price: 400, inStock: true }
];
// 1. Filter in-stock items
const availableItems = cart.filter(product => product.inStock);
// 2. Calculate total price with reduce
const totalPrice = availableItems.reduce((acc, curr) => acc + curr.price, 0);
// 3. Extract item names with map
const itemNames = availableItems.map(p => p.item);
console.log("Available Items:", itemNames);
console.log("Cart Total: $" + totalPrice);Expected Output:
Available Items: [ 'Mechanical Keyboard', 'Wireless Mouse', '4K Monitor' ] Cart Total: $565
How It Works: Step-by-Step
- Line 10: filter() returns items where inStock === true.
- Line 13: reduce() accumulates item prices starting from initial value 0.
- Line 16: map() transforms object array into string array of item names.
Key Concepts
- Array methods like map, filter, and reduce do not mutate the original array.
- Use find() to locate the first matching element, or findIndex() for its index.
- Use includes() for simple primitive existence checks.
Common Mistake: Forgetting the initial value in reduce()
Calling reduce without an initial value uses the first element as accumulator, which breaks on empty arrays.
❌ Incorrect
[].reduce((a, b) => a + b) // TypeError: Reduce of empty array with no initial value
✅ Correct
[].reduce((a, b) => a + b, 0) // Returns 0 safely
Related JavaScript Tutorials & Compiler
JavaScript Objects and Map: Key-Value Data Structures
Learn differences between plain JavaScript Objects and the ES6 Map collection.
JavaScript Set: Unique Collections and Deduplication
Learn how to store unique values of any type using the ES6 Set object.
JavaScript Strings: Template Literals, Regex, and Methods
Explore string methods (split, replace, trim, includes) and template strings.
JavaScript Online Compiler
Open in Compilra IDE
Run and test JavaScript on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.