惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

WordPress大学
WordPress大学
J
Java Code Geeks
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
腾讯CDC
IT之家
IT之家
罗磊的独立博客
酷 壳 – CoolShell
酷 壳 – CoolShell
U
Unit 42
爱范儿
爱范儿
博客园 - 聂微东
F
Fortinet All Blogs
V
Visual Studio Blog
Blog — PlanetScale
Blog — PlanetScale
G
Google Developers Blog
aimingoo的专栏
aimingoo的专栏
L
LangChain Blog
雷峰网
雷峰网
B
Blog RSS Feed
宝玉的分享
宝玉的分享
T
Tailwind CSS Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Engineering at Meta
Engineering at Meta
H
Hackread – Cybersecurity News, Data Breaches, AI and More

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
JavaScript Array Methods: The Complete Visual Guide
Alex Chen · 2026-05-16 · via DEV Community

JavaScript Array Methods: The Complete Visual Guide

Master these methods and you'll write 50% less code.

The Map: Array Method Categories

┌─────────────────────────────────────────┐
│           JavaScript Arrays              │
├─────────┬──────────┬──────────┬─────────┤
│ Iterate │ Transform │  Filter  │ Reduce  │
├─────────┼──────────┼──────────┼─────────┤
│ forEach │ map       │ filter   │ reduce  │
│ for...of │ flatMap   │ find     │ some    │
│         │ sort      │ findIndex│ every   │
│         │ reverse   │ includes │ join    │
│         │ slice     │ splice   │ toString│
├─────────┼──────────┼──────────┼─────────┤
│         │          │          │         │
│  "Do"   │  "New"   │ "Pick"   │ "Result"│
└─────────┴──────────┴──────────┴─────────┘

Enter fullscreen mode Exit fullscreen mode

1. map() — Transform Every Element

const numbers = [1, 2, 3, 4, 5];

// Double every number
numbers.map(n => n * 2);        // [2, 4, 6, 8, 10]

// Extract property from objects
const users = [{ name: 'Alex', age: 30 }, { name: 'Sam', age: 25 }];
users.map(u => u.name);         // ['Alex', 'Sam']

// Convert types
const strings = ['1', '2', '3'];
strings.map(Number);             // [1, 2, 3]

Enter fullscreen mode Exit fullscreen mode

2. filter() — Keep Elements That Pass a Test

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// Even numbers only
numbers.filter(n => n % 2 === 0); // [2, 4, 6, 8, 10]

// Active users
const users = [
  { name: 'Alex', active: true },
  { name: 'Bob', active: false },
  { name: 'Charlie', active: true },
];
users.filter(u => u.active);     // [{ name: 'Alex' }, { name: 'Charlie' }]

// Remove falsy values
const mixed = [0, 1, '', 'hello', null, undefined, false, 42];
mixed.filter(Boolean);           // [1, 'hello', 42]

Enter fullscreen mode Exit fullscreen mode

3. reduce() — Transform Array Into Anything

const numbers = [1, 2, 3, 4, 5];

// Sum
numbers.reduce((sum, n) => sum + n, 0);  // 15

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

// Flatten (use flat() instead though)
const nested = [[1, 2], [3, 4], [5]];
nested.reduce((flat, arr) => [...flat, ...arr], []); // [1, 2, 3, 4, 5]

// Group by property
const people = [
  { name: 'Alex', dept: 'Engineering' },
  { name: 'Sam', dept: 'Marketing' },
  { name: 'Charlie', dept: 'Engineering' },
];
people.reduce((groups, person) => {
  (groups[person.dept] ??= []).push(person);
  return groups;
}, {});
// { Engineering: [...], Marketing: [...] }

Enter fullscreen mode Exit fullscreen mode

4. find() and findIndex()

const users = [
  { id: 1, name: 'Alex', role: 'admin' },
  { id: 2, name: 'Sam', role: 'user' },
  { id: 3, name: 'Charlie', role: 'admin' },
];

// Find first admin
users.find(u => u.role === 'admin');    // { id: 1, name: 'Alex', role: 'admin' }

// Find by id
users.find(u => u.id === 2);            // { id: 2, name: 'Sam', role: 'user' }

// Index of first admin
users.findIndex(u => u.role === 'admin'); // 0

// Not found → undefined
users.find(u => u.id === 999);          // undefined

Enter fullscreen mode Exit fullscreen mode

5. some() and every()

const numbers = [2, 4, 6, 8, 10];

// Is at least one even? (always true here, but example)
numbers.some(n => n > 5);     // true

// Are ALL numbers even?
numbers.every(n => n % 2 === 0); // true

// Real use case: form validation
const form = { email: 'test@x.com', password: 'abc123', name: '' };

const isValid = Object.values(form).every(Boolean); // false (name is empty)

// Real use case: permissions check
const userPermissions = ['read', 'write'];
const hasWrite = userPermissions.includes('write'); // true
const isAdmin = userPermissions.includes('admin'); // false

Enter fullscreen mode Exit fullscreen mode

6. sort() — Sort Elements

const nums = [3, 1, 4, 1, 5, 9, 2, 6];
nums.sort((a, b) => a - b);      // [1, 1, 2, 3, 4, 5, 6, 9] ascending
nums.sort((a, b) => b - a);      // [9, 6, 5, 4, 3, 2, 1, 1] descending

// Sort objects by property
const users = [
  { name: 'Charlie', age: 25 },
  { name: 'Alex', age: 30 },
  { name: 'Sam', age: 28 },
];

users.sort((a, b) => a.age - b);    // Youngest first
users.sort((a, b) => a.name.localeCompare(b.name)); // Alphabetical

// ⚠️ sort() mutates the original array!
// Use .toSorted() (ES2023) for a new array:
const sorted = nums.toSorted((a, b) => a - b);

Enter fullscreen mode Exit fullscreen mode

7. flat() and flatMap()

// Flatten nested arrays
const nested = [1, [2, 3], [4, [5, 6]]];
nested.flat();          // [1, 2, 3, 4, [5, 6]] (one level)
nested.flat(Infinity);  // [1, 2, 3, 4, 5, 6] (all levels)

// flatMap = map + flat (one step)
const sentences = ['hello world', 'foo bar baz'];

sentences.flatMap(s => s.split(' '));
// ['hello', 'world', 'foo', 'bar', 'baz']

// Practical: Filter + Transform in one step
const users = [
  { name: 'Alex', posts: 10 },
  { name: 'Bob', posts: 0 },
  { name: 'Charlie', posts: 5 },
];

users.flatMap(u => u.posts > 0 ? [u.name] : []);
// ['Alex', 'Charlie'] (filter AND extract)

Enter fullscreen mode Exit fullscreen mode

8. slice() and splice()

const arr = [1, 2, 3, 4, 5];

// slice: Extract without modifying original
arr.slice(1, 3);     // [2, 3]
arr.slice(-2);        // [4, 5]
arr.slice(2);         // [3, 4, 5]
// arr is still [1, 2, 3, 4, 5]

// splice: Modify original (remove, insert, replace)
const removed = arr.splice(1, 2); // Remove 2 elements from index 1
// arr is now [1, 4, 5], removed is [2, 3]

// Insert at index
arr.splice(1, 0, 2, 3); // Insert 2, 3 at index 1
// arr is now [1, 2, 3, 4, 5]

Enter fullscreen mode Exit fullscreen mode

9. includes() — Simple Existence Check

const colors = ['red', 'green', 'blue'];
colors.includes('green');   // true
colors.includes('yellow');  // false

// More readable than indexOf:
// Old: colors.indexOf('green') !== -1
// New: colors.includes('green')

Enter fullscreen mode Exit fullscreen mode

10. Chaining Methods

const users = [
  { name: 'Alex', age: 30, role: 'admin', active: true },
  { name: 'Bob', age: 20, role: 'user', active: false },
  { name: 'Charlie', age: 25, role: 'user', active: true },
  { name: 'Diana', age: 35, role: 'admin', active: true },
];

// Get names of active users over 25, sorted by age
const result = users
  .filter(u => u.active)       // Keep active
  .filter(u => u.age > 25)     // Keep over 25
  .sort((a, b) => a.age - b)  // Sort by age
  .map(u => u.name);           // Extract names

// ['Alex', 'Diana']

// Average age of active admins
const avgAge = users
  .filter(u => u.role === 'admin' && u.active)
  .map(u => u.age)
  .reduce((sum, age, _, arr) => sum + age / arr.length, 0);

// 32.5

Enter fullscreen mode Exit fullscreen mode

Quick Reference

Method Returns Mutates? Use Case
map() New array No Transform elements
filter() New array No Keep matching elements
reduce() Any value No Accumulate into one value
find() Element or undefined No Find first match
findIndex() Index or -1 No Find index of first match
some() Boolean No At least one matches?
every() Boolean No All match?
includes() Boolean No Contains value?
sort() Same array Yes Sort elements
flat() New array No Flatten nested arrays
flatMap() New array No Map + flatten
slice() New array No Extract portion
splice() Removed elements Yes Insert/remove/replace

Which array method do you use most? Any I missed?

Follow @armorbreak for more JavaScript content.