JavaScript:JavaScript Arrays: Methods (map, filter, reduce, slice)
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:

ParameterTypeDescription
map()Array MethodCreates a new array with results of calling a function on every item.
filter()Array MethodCreates a new array with elements that pass the test function.
reduce()Array MethodReduces array to a single accumulator value.

Ready-to-Run Code Example

Executable in Compilra

Run 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

Run and test JavaScript on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

JavaScript Online Compiler