javascript 211 lines · 1 tab

Array methods: map, filter, reduce, and functional programming

Alex Chang Feb 2026
1 tab
// Sample data
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const users = [
  { id: 1, name: 'Alice', age: 25, active: true },
  { id: 2, name: 'Bob', age: 30, active: false },
  { id: 3, name: 'Charlie', age: 35, active: true },
  { id: 4, name: 'Diana', age: 28, active: true }
];

// MAP - Transform each element
const doubled = numbers.map(n => n * 2);
console.log(doubled); // [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

const names = users.map(user => user.name);
console.log(names); // ['Alice', 'Bob', 'Charlie', 'Diana']

const userSummaries = users.map(user => ({
  id: user.id,
  summary: `${user.name} (${user.age})`
}));

// FILTER - Select elements matching criteria
const evens = numbers.filter(n => n % 2 === 0);
console.log(evens); // [2, 4, 6, 8, 10]

const activeUsers = users.filter(user => user.active);
console.log(activeUsers); // Alice, Charlie, Diana

const adults = users.filter(user => user.age >= 30);
console.log(adults); // Bob, Charlie

// REDUCE - Accumulate to single value
const sum = numbers.reduce((acc, n) => acc + n, 0);
console.log(sum); // 55

const product = numbers.reduce((acc, n) => acc * n, 1);
console.log(product); // 3628800

const usersByName = users.reduce((acc, user) => {
  acc[user.name] = user;
  return acc;
}, {});
console.log(usersByName);
// { Alice: {...}, Bob: {...}, ... }

// Count occurrences
const fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple'];
const fruitCounts = fruits.reduce((acc, fruit) => {
  acc[fruit] = (acc[fruit] || 0) + 1;
  return acc;
}, {});
console.log(fruitCounts);
// { apple: 3, banana: 2, orange: 1 }

// FIND - Get first matching element
const firstEven = numbers.find(n => n % 2 === 0);
console.log(firstEven); // 2

const charlie = users.find(user => user.name === 'Charlie');
console.log(charlie); // { id: 3, name: 'Charlie', ... }

// FIND INDEX
const charlieIndex = users.findIndex(user => user.name === 'Charlie');
console.log(charlieIndex); // 2

// SOME - Test if any match
const hasAdults = users.some(user => user.age >= 30);
console.log(hasAdults); // true

const hasTeens = users.some(user => user.age < 20);
console.log(hasTeens); // false

// EVERY - Test if all match
const allActive = users.every(user => user.active);
console.log(allActive); // false

const allAdults = users.every(user => user.age >= 18);
console.log(allAdults); // true

// FOREACH - Iterate (no return value)
users.forEach(user => {
  console.log(`${user.name} is ${user.age} years old`);
});

// SORT - Order elements (mutates array!)
const sortedByAge = [...users].sort((a, b) => a.age - b.age);
const sortedByName = [...users].sort((a, b) =>
  a.name.localeCompare(b.name)
);

// SLICE - Extract portion (non-mutating)
const firstThree = numbers.slice(0, 3);
console.log(firstThree); // [1, 2, 3]

const lastThree = numbers.slice(-3);
console.log(lastThree); // [8, 9, 10]

// FLAT - Flatten nested arrays
const nested = [1, [2, 3], [4, [5, 6]]];
const flat1 = nested.flat();
console.log(flat1); // [1, 2, 3, 4, [5, 6]]

const flat2 = nested.flat(2);
console.log(flat2); // [1, 2, 3, 4, 5, 6]

// FLATMAP - Map then flatten
const words = ['hello world', 'foo bar'];
const allWords = words.flatMap(phrase => phrase.split(' '));
console.log(allWords); // ['hello', 'world', 'foo', 'bar']

// Method chaining - powerful combinations
const result = users
  .filter(user => user.active)           // Get active users
  .map(user => ({ ...user, age: user.age + 1 })) // Increment age
  .sort((a, b) => a.age - b.age)         // Sort by age
  .map(user => user.name);               // Extract names

console.log(result); // ['Alice', 'Diana', 'Charlie']

// Complex example: Group and count
const transactions = [
  { type: 'deposit', amount: 100 },
  { type: 'withdrawal', amount: 50 },
  { type: 'deposit', amount: 200 },
  { type: 'withdrawal', amount: 30 }
];

const summary = transactions.reduce((acc, transaction) => {
  if (!acc[transaction.type]) {
    acc[transaction.type] = { count: 0, total: 0 };
  }
  acc[transaction.type].count++;
  acc[transaction.type].total += transaction.amount;
  return acc;
}, {});

console.log(summary);
// { deposit: { count: 2, total: 300 }, withdrawal: { count: 2, total: 80 } }

// Unique values
const duplicates = [1, 2, 2, 3, 3, 3, 4, 5, 5];
const unique = [...new Set(duplicates)];
console.log(unique); // [1, 2, 3, 4, 5]

// Or using filter
const uniqueFilter = duplicates.filter((item, index, arr) =>
  arr.indexOf(item) === index
);

// Array intersection
const arr1 = [1, 2, 3, 4, 5];
const arr2 = [3, 4, 5, 6, 7];
const intersection = arr1.filter(item => arr2.includes(item));
console.log(intersection); // [3, 4, 5]

// Array difference
const difference = arr1.filter(item => !arr2.includes(item));
console.log(difference); // [1, 2]

// Partition array
function partition(arr, predicate) {
  return arr.reduce((acc, item) => {
    acc[predicate(item) ? 0 : 1].push(item);
    return acc;
  }, [[], []]);
}

const [evensPartition, oddsPartition] = partition(
  numbers,
  n => n % 2 === 0
);

// Chunking array
function chunk(arr, size) {
  return arr.reduce((acc, _, i) => {
    if (i % size === 0) {
      acc.push(arr.slice(i, i + size));
    }
    return acc;
  }, []);
}

console.log(chunk(numbers, 3));
// [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]

// Compose transformations
const pipeline = [
  arr => arr.filter(n => n % 2 === 0),
  arr => arr.map(n => n * 2),
  arr => arr.reduce((sum, n) => sum + n, 0)
];

const pipelineResult = pipeline.reduce(
  (value, fn) => fn(value),
  numbers
);
console.log(pipelineResult); // Sum of doubled evens

// Object from array
const keyValuePairs = users.map(user => [user.id, user.name]);
const userMap = Object.fromEntries(keyValuePairs);
console.log(userMap); // { 1: 'Alice', 2: 'Bob', ... }

// Flat map real example
const authors = [
  { name: 'Author 1', books: ['Book A', 'Book B'] },
  { name: 'Author 2', books: ['Book C'] }
];

const allBooks = authors.flatMap(author => author.books);
console.log(allBooks); // ['Book A', 'Book B', 'Book C']
1 file · javascript Explain with highlit

Array methods enable functional programming patterns in JavaScript. The .map() method transforms each element and returns new array. I use .filter() to create arrays with elements meeting criteria. The .reduce() method accumulates values into single result with accumulator and current value. Using .forEach() iterates without returning new array. The .find() returns first matching element while .findIndex() returns its index. The .some() tests if any element passes test; .every() tests if all pass. The .flat() flattens nested arrays while .flatMap() combines map and flat. Method chaining creates pipelines for data transformation. These methods don't mutate original arrays, supporting immutability. Understanding array methods is fundamental to modern JavaScript.


Related snips

javascript
// Creating a Promise
const myPromise = new Promise((resolve, reject) => {
  const success = true;

  setTimeout(() => {
    if (success) {

Promises and async/await patterns for asynchronous JavaScript

javascript promises async-await
by Alex Chang 1 tab
javascript
import { Controller } from "@hotwired/stimulus"
import Mousetrap from "mousetrap"

export default class extends Controller {
  connect() {
    // Global shortcuts

Keyboard shortcuts with Stimulus and Mousetrap

stimulus javascript ux
by Jordan Lee 2 tabs
javascript
// Get canvas and context
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');

// 1. Basic shapes
// Rectangle (filled)

Canvas API for graphics and animations

canvas javascript graphics
by Alex Chang 1 tab
javascript
// Basic event listener
const button = document.getElementById('myButton');

button.addEventListener('click', function(event) {
  console.log('Button clicked!');
  console.log('Event type:', event.type);

Event handling and event delegation patterns in JavaScript

javascript events event-delegation
by Alex Chang 1 tab
javascript
// Basic GET request
fetch('https://api.example.com/users')
  .then(response => {
    console.log('Status:', response.status);
    console.log('OK:', response.ok);
    return response.json();

Fetch API for HTTP requests and AJAX communication

javascript fetch api
by Alex Chang 1 tab
erb
<turbo-stream action="set_title">
  <template><%= "Inbox (#{@unread_count})" %></template>
</turbo-stream>

Turbo Streams: update document title with a custom action

rails hotwire turbo
by Henry Kim 2 tabs

Share this code

Here's the card — post it anywhere.

Array methods: map, filter, reduce, and functional programming — share card
Link copied