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

推荐订阅源

L
LINUX DO - 最新话题
NISL@THU
NISL@THU
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
P
Privacy & Cybersecurity Law Blog
Schneier on Security
Schneier on Security
宝玉的分享
宝玉的分享
Cisco Talos Blog
Cisco Talos Blog
Help Net Security
Help Net Security
月光博客
月光博客
V
V2EX
量子位
T
Threat Research - Cisco Blogs
A
About on SuperTechFans
Google DeepMind News
Google DeepMind News
Google DeepMind News
Google DeepMind News
P
Privacy International News Feed
S
Secure Thoughts
T
The Exploit Database - CXSecurity.com
P
Proofpoint News Feed
C
CXSECURITY Database RSS Feed - CXSecurity.com
Engineering at Meta
Engineering at Meta
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
A
Arctic Wolf
S
Schneier on Security
H
Hacker News: Front Page
P
Proofpoint News Feed
MyScale Blog
MyScale Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
C
Cisco Blogs
G
GRAHAM CLULEY
The Cloudflare Blog
博客园 - Franky
N
News and Events Feed by Topic
TaoSecurity Blog
TaoSecurity Blog
云风的 BLOG
云风的 BLOG
H
Heimdal Security Blog
The GitHub Blog
The GitHub Blog
C
Check Point Blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main
T
The Blog of Author Tim Ferriss
小众软件
小众软件
Hacker News: Ask HN
Hacker News: Ask HN
T
Tenable Blog
The Last Watchdog
The Last Watchdog
J
Java Code Geeks
T
Troy Hunt's Blog
B
Blog
Blog — PlanetScale
Blog — PlanetScale
腾讯CDC

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 Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Array Methods You Must Know
Pratham · 2026-05-10 · via DEV Community

The six methods that turn JavaScript arrays from basic lists into powerful tools.


When I first learned arrays, I thought I was done. Create an array, access elements by index, loop through them with for — what else is there? Then I discovered array methods, and it felt like upgrading from a bicycle to a car.

Array methods are built-in functions that every array comes with. They let you add, remove, transform, filter, and reduce data — often in a single line of code. No manual loops, no index tracking, no off-by-one errors. Just tell the array what you want, and it handles the how.

In the ChaiCode Web Dev Cohort 2026, array methods came up almost immediately after we learned the basics. And honestly, these six methods cover probably 90% of what you'll ever do with arrays in real projects. Let's go through each one.


1. push() and pop() — Adding and Removing from the End

These two are the simplest array methods. They work on the end of the array.

push() — Add to the End

const fruits = ["Apple", "Mango"];
console.log(fruits); // ["Apple", "Mango"]

fruits.push("Banana");
console.log(fruits); // ["Apple", "Mango", "Banana"]

fruits.push("Grapes", "Orange"); // You can push multiple at once
console.log(fruits); // ["Apple", "Mango", "Banana", "Grapes", "Orange"]

Enter fullscreen mode Exit fullscreen mode

push() modifies the original array and returns the new length.

const newLength = fruits.push("Kiwi");
console.log(newLength); // 6

Enter fullscreen mode Exit fullscreen mode

pop() — Remove from the End

const fruits = ["Apple", "Mango", "Banana"];
console.log(fruits); // ["Apple", "Mango", "Banana"]

const removed = fruits.pop();
console.log(removed); // "Banana" — the removed element
console.log(fruits); // ["Apple", "Mango"] — Banana is gone

Enter fullscreen mode Exit fullscreen mode

pop() removes the last element, returns it, and shrinks the array by one.

Before and After

push("Banana"):
  Before: ["Apple", "Mango"]             → length: 2
  After:  ["Apple", "Mango", "Banana"]   → length: 3
                              ↑ added

pop():
  Before: ["Apple", "Mango", "Banana"]   → length: 3
  After:  ["Apple", "Mango"]             → length: 2
                              ↑ removed (returned "Banana")

Enter fullscreen mode Exit fullscreen mode


2. shift() and unshift() — Adding and Removing from the Start

These work just like push() and pop(), but on the beginning of the array.

unshift() — Add to the Start

const tasks = ["Study", "Exercise"];
console.log(tasks); // ["Study", "Exercise"]

tasks.unshift("Wake up");
console.log(tasks); // ["Wake up", "Study", "Exercise"]

Enter fullscreen mode Exit fullscreen mode

shift() — Remove from the Start

const tasks = ["Wake up", "Study", "Exercise"];
console.log(tasks); // ["Wake up", "Study", "Exercise"]

const first = tasks.shift();
console.log(first); // "Wake up"
console.log(tasks); // ["Study", "Exercise"]

Enter fullscreen mode Exit fullscreen mode

Quick Reference: The Four Basic Methods

Method What It Does Position Modifies Original Returns
push() Adds element(s) End ✅ Yes New length
pop() Removes one element End ✅ Yes Removed element
unshift() Adds element(s) Start ✅ Yes New length
shift() Removes one element Start ✅ Yes Removed element

Think of it this way: push/pop work on the right side. unshift/shift work on the left side.


3. forEach() — Do Something with Each Element

forEach() is the simplest iteration method. It runs a function once for every element in the array. It's basically a cleaner replacement for a for loop when you just want to do something with each element (not transform or filter).

Traditional for Loop

const names = ["Pratham", "Arjun", "Priya"];

for (let i = 0; i < names.length; i++) {
  console.log(`Hello, ${names[i]}!`);
}

Enter fullscreen mode Exit fullscreen mode

Same Thing with forEach()

const names = ["Pratham", "Arjun", "Priya"];

names.forEach((name) => {
  console.log(`Hello, ${name}!`);
});
// Hello, Pratham!
// Hello, Arjun!
// Hello, Priya!

Enter fullscreen mode Exit fullscreen mode

No index tracking, no .length check, no i++. You just tell it what to do with each element.

The Callback Gets Three Arguments

const scores = [85, 92, 78];

scores.forEach((score, index, array) => {
  console.log(`Score ${index + 1}: ${score} (out of ${array.length} total)`);
});
// Score 1: 85 (out of 3 total)
// Score 2: 92 (out of 3 total)
// Score 3: 78 (out of 3 total)

Enter fullscreen mode Exit fullscreen mode

Most of the time you'll only use the first argument (the element). The index and full array are there if you need them.

Important: forEach() Returns Nothing

const result = [1, 2, 3].forEach((n) => n * 2);
console.log(result); // undefined

Enter fullscreen mode Exit fullscreen mode

forEach() is for side effects — logging, updating DOM elements, making API calls. If you need a new array back, use map().


4. map() — Transform Every Element

map() is one of the most important array methods you'll ever learn. It creates a new array by running a function on every element of the original array.

Think of it as: "Take each item, transform it, and give me back a new array of the results."

Example: Doubling Numbers

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

const doubled = numbers.map((num) => num * 2);

console.log(doubled); // [2, 4, 6, 8, 10]
console.log(numbers); // [1, 2, 3, 4, 5] — original unchanged

Enter fullscreen mode Exit fullscreen mode

Traditional for Loop vs map()

// ❌ Traditional way — manual, more code
const numbers = [1, 2, 3, 4, 5];
const doubled = [];
for (let i = 0; i < numbers.length; i++) {
  doubled.push(numbers[i] * 2);
}

// ✅ With map() — one line, declarative
const doubled = numbers.map((num) => num * 2);

Enter fullscreen mode Exit fullscreen mode

Same result. But map() is shorter, doesn't require creating an empty array first, and clearly states its intent: "I'm transforming each element."

Flowchart: How map() Works

Original Array:    [1,    2,    3,    4,    5]
                    ↓     ↓     ↓     ↓     ↓
Callback:        num*2  num*2  num*2  num*2  num*2
                    ↓     ↓     ↓     ↓     ↓
New Array:         [2,    4,    6,    8,    10]

• Each element goes through the callback function
• Each result lands in the same position in the NEW array
• Original array is UNTOUCHED

Enter fullscreen mode Exit fullscreen mode

More Examples

// Convert names to uppercase
const names = ["pratham", "arjun", "priya"];
const uppercased = names.map((name) => name.toUpperCase());
console.log(uppercased); // ["PRATHAM", "ARJUN", "PRIYA"]

// Extract a property from objects
const users = [
  { name: "Pratham", age: 22 },
  { name: "Arjun", age: 21 },
  { name: "Priya", age: 23 },
];
const userNames = users.map((user) => user.name);
console.log(userNames); // ["Pratham", "Arjun", "Priya"]

// Add formatting
const prices = [100, 250, 500];
const formatted = prices.map((price) => `₹${price}.00`);
console.log(formatted); // ["₹100.00", "₹250.00", "₹500.00"]

Enter fullscreen mode Exit fullscreen mode


5. filter() — Keep Only What Matches

filter() creates a new array containing only the elements that pass a test (return true from the callback).

Think of it as: "Go through each item. Keep it if the condition is true. Throw it away if it's false."

Example: Get Even Numbers

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

const evens = numbers.filter((num) => num % 2 === 0);

console.log(evens); // [2, 4, 6, 8, 10]
console.log(numbers); // [1, 2, 3, ..., 10] — original unchanged

Enter fullscreen mode Exit fullscreen mode

Flowchart: How filter() Works

Original Array:  [1,     2,     3,     4,     5,     6]
                  ↓      ↓      ↓      ↓      ↓      ↓
Test:           odd?   even?  odd?   even?  odd?   even?
                  ↓      ↓      ↓      ↓      ↓      ↓
Result:         false   true   false  true   false  true
                  ✗      ✓      ✗      ✓      ✗      ✓
                         ↓             ↓             ↓
New Array:             [ 2,            4,             6]

• Each element is tested by the callback
• true → element is KEPT in the new array
• false → element is EXCLUDED
• Original array is UNTOUCHED

Enter fullscreen mode Exit fullscreen mode

Traditional for Loop vs filter()

// ❌ Traditional way
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const evens = [];
for (let i = 0; i < numbers.length; i++) {
  if (numbers[i] % 2 === 0) {
    evens.push(numbers[i]);
  }
}

// ✅ With filter() — one line
const evens = numbers.filter((num) => num % 2 === 0);

Enter fullscreen mode Exit fullscreen mode

More Examples

// Filter adults
const ages = [15, 22, 17, 30, 12, 25, 8];
const adults = ages.filter((age) => age >= 18);
console.log(adults); // [22, 30, 25]

// Filter active users
const users = [
  { name: "Pratham", active: true },
  { name: "Arjun", active: false },
  { name: "Priya", active: true },
];
const activeUsers = users.filter((user) => user.active);
console.log(activeUsers);
// [{ name: "Pratham", active: true }, { name: "Priya", active: true }]

// Filter long strings
const words = ["hi", "hello", "hey", "greetings", "yo"];
const longWords = words.filter((word) => word.length > 3);
console.log(longWords); // ["hello", "greetings"]

Enter fullscreen mode Exit fullscreen mode


6. reduce() — Boil Everything Down to One Value

reduce() is the most powerful — and the most confusing at first — array method. It takes an entire array and reduces it down to a single value by accumulating a result as it goes through each element.

Think of it as a snowball rolling downhill, picking up snow as it goes. It starts small and gets bigger with each element it processes.

Basic Syntax

array.reduce((accumulator, currentValue) => {
  // do something
  return updatedAccumulator;
}, initialValue);

Enter fullscreen mode Exit fullscreen mode

  • accumulator — the running total (the snowball)
  • currentValue — the current element being processed
  • initialValue — what the accumulator starts as

Example: Sum of Numbers

const numbers = [10, 20, 30, 40];

const total = numbers.reduce((sum, num) => sum + num, 0);

console.log(total); // 100

Enter fullscreen mode Exit fullscreen mode

Visual: How reduce() Accumulates

Initial value: 0

Step 1:  sum = 0   + 10  →  10
Step 2:  sum = 10  + 20  →  30
Step 3:  sum = 30  + 30  →  60
Step 4:  sum = 60  + 40  →  100

Final result: 100

Think of it as:
[10, 20, 30, 40]  →  0 + 10 + 20 + 30 + 40  →  100
 entire array          accumulated step by step    one value

Enter fullscreen mode Exit fullscreen mode

Step-by-Step Breakdown

Let me trace through each iteration so there's zero confusion:

const numbers = [10, 20, 30, 40];

const total = numbers.reduce((sum, num) => {
  console.log(`sum: ${sum}, num: ${num}, result: ${sum + num}`);
  return sum + num;
}, 0);

// sum: 0, num: 10, result: 10
// sum: 10, num: 20, result: 30
// sum: 30, num: 30, result: 60
// sum: 60, num: 40, result: 100

console.log(total); // 100

Enter fullscreen mode Exit fullscreen mode

Each time, the returned value becomes the new sum for the next iteration. The final returned value is the result.

More Examples

// Find the maximum value
const scores = [85, 92, 78, 95, 88];

const highest = scores.reduce((max, score) => (score > max ? score : max), 0);
console.log(highest); // 95

// Count occurrences
const votes = ["yes", "no", "yes", "yes", "no", "yes"];

const tally = votes.reduce((counts, vote) => {
  counts[vote] = (counts[vote] || 0) + 1;
  return counts;
}, {});
console.log(tally); // { yes: 4, no: 2 }

Enter fullscreen mode Exit fullscreen mode

Don't worry if reduce() feels tricky right now. It took me a few days of practice before I stopped needing to trace through every step manually. The key is to always ask: "What is the accumulator, and how does each element change it?"


map() vs filter() vs forEach() — When to Use Which

Method Returns Use When Modifies Original
forEach() undefined You want to do something (side effects) ❌ No
map() New array You want to transform each element ❌ No
filter() New array You want to keep elements that pass a test ❌ No
reduce() Single value You want to accumulate into one result ❌ No

Rule of thumb:

  • Need to log or update something? → forEach()
  • Need a new array of transformed values? → map()
  • Need a new array with some elements removed? → filter()
  • Need one final value from the whole array? → reduce()

Let's Practice: Hands-On Assignment

Part 1: Create an Array of Numbers

const numbers = [3, 7, 12, 5, 18, 22, 9, 15, 2, 30];
console.log("Original:", numbers);
// Original: [3, 7, 12, 5, 18, 22, 9, 15, 2, 30]

Enter fullscreen mode Exit fullscreen mode

Part 2: Use map() to Double Each Number

const doubled = numbers.map((num) => num * 2);
console.log("Doubled:", doubled);
// Doubled: [6, 14, 24, 10, 36, 44, 18, 30, 4, 60]

Enter fullscreen mode Exit fullscreen mode

Part 3: Use filter() to Get Numbers Greater Than 10

const greaterThanTen = numbers.filter((num) => num > 10);
console.log("Greater than 10:", greaterThanTen);
// Greater than 10: [12, 18, 22, 15, 30]

Enter fullscreen mode Exit fullscreen mode

Part 4: Use reduce() to Calculate Total Sum

const totalSum = numbers.reduce((sum, num) => sum + num, 0);
console.log("Total sum:", totalSum);
// Total sum: 123

Enter fullscreen mode Exit fullscreen mode

Part 5: Combine Them (Bonus)

// Double the numbers, keep only those above 20, then sum them
const result = numbers
  .map((num) => num * 2)
  .filter((num) => num > 20)
  .reduce((sum, num) => sum + num, 0);

console.log("Final result:", result);
// Doubled: [6, 14, 24, 10, 36, 44, 18, 30, 4, 60]
// Filtered (>20): [24, 36, 44, 30, 60]
// Sum: 194

Enter fullscreen mode Exit fullscreen mode

I know I said "avoid chaining initially" — but once you understand each method individually, seeing them chained together shows you why these methods are so powerful. Each one passes its result to the next.


Key Takeaways

  1. push()/pop() add and remove from the end. unshift()/shift() add and remove from the start. All four modify the original array.
  2. forEach() runs a function on each element for side effects. It returns nothing.
  3. map() transforms every element and returns a new array. The original stays unchanged.
  4. filter() tests every element and returns a new array with only the ones that passed. The original stays unchanged.
  5. reduce() accumulates the entire array into a single value. Start with the accumulator and initial value, and build up step by step.

Wrapping Up

These six methods are the workhorses of JavaScript. In real projects — whether you're building a to-do app, filtering search results, calculating cart totals, or rendering lists in React — you'll reach for map(), filter(), and reduce() constantly. The basic push(), pop(), shift(), and unshift() handle the simpler add/remove operations.

My advice: open your browser console right now and try every example in this article. Don't just read them — type them. Change the numbers. Break things. That's how these methods become second nature.

I'm learning all of this through the ChaiCode Web Dev Cohort 2026 under Hitesh Chaudhary and Piyush Garg, and array methods were the turning point where JavaScript started feeling genuinely fun. Once you can transform, filter, and reduce data in one line, you feel like you can build anything.

Connect with me on LinkedIn or visit PrathamDEV.in. More articles coming as the journey continues.

Happy coding! 🚀


Written by Pratham Bhardwaj | Web Dev Cohort 2026, ChaiCode