Skip to content
Happy Programming Guide
Start learning
JavaScript

JavaScript Arrays Explained (Including map, filter and reduce)

Creating arrays, adding and removing items, and the three methods you will use constantly — map, filter and reduce — explained with small examples.

An array holds several values in order under one name.

JavaScript
const fruits = ["apple", "banana", "mango"];

console.log(fruits[0]);        // apple
console.log(fruits.length);    // 3

Positions start at 0, so the last item is always at length - 1.

Adding and removing#

JavaScript
const items = ["a", "b"];

items.push("c");        // add to the end     → ["a","b","c"]
items.pop();            // remove from end    → ["a","b"]
items.unshift("z");     // add to the start   → ["z","a","b"]
items.shift();          // remove from start  → ["a","b"]

These four change the array in place. Note that this works even on a const array — const only stops the name being reassigned.

Copying and combining#

JavaScript
const a = [1, 2];
const b = [3, 4];

const joined = [...a, ...b];    // [1, 2, 3, 4]
const copy = [...a];            // a genuine copy
const alias = a;                // NOT a copy — both names, one array

map: transform every item#

“Give me a new array where each item has been changed the same way.”

JavaScript
const prices = [100, 250, 80];

const withTax = prices.map(p => Math.round(p * 1.17));
console.log(withTax);   // [117, 293, 94]

const names = ["ada", "sam"];
const capitals = names.map(n => n[0].toUpperCase() + n.slice(1));

map always returns an array of the same length. The original is untouched.

filter: keep some items#

“Give me a new array containing only the items that pass this test.”

JavaScript
const numbers = [4, 9, 12, 3];

const big = numbers.filter(n => n > 5);        // [9, 12]
const even = numbers.filter(n => n % 2 === 0); // [4, 12]

The function you pass must return true or false. Returning something else leads to surprising results.

reduce: boil the array down to one value#

“Walk through the array carrying a running result.”

JavaScript
const prices = [100, 250, 80];

const total = prices.reduce((sum, price) => sum + price, 0);
console.log(total);   // 430

The 0 at the end is the starting value. On each pass, sum is the result so far and price is the current item.

It is not only for adding:

JavaScript
const words = ["code", "test", "code"];

const counts = words.reduce((tally, word) => {
  tally[word] = (tally[word] || 0) + 1;
  return tally;
}, {});

console.log(counts);   // { code: 2, test: 1 }

Chaining them#

JavaScript
const orders = [
  { item: "pen", price: 50, paid: true },
  { item: "book", price: 300, paid: false },
  { item: "bag", price: 1200, paid: true },
];

const paidTotal = orders
  .filter(o => o.paid)
  .map(o => o.price)
  .reduce((sum, p) => sum + p, 0);

console.log(paidTotal);   // 1250

Each step is small and readable, which is why this style is everywhere in modern JavaScript.

Searching#

JavaScript
const users = [{ name: "Ada" }, { name: "Sam" }];

users.find(u => u.name === "Sam");        // the object, or undefined
users.findIndex(u => u.name === "Sam");   // 1, or -1
users.some(u => u.name === "Ada");        // true  — is any?
users.every(u => u.name.length > 2);      // true  — are all?
["a", "b"].includes("a");                 // true

Sorting numbers correctly#

JavaScript
const numbers = [10, 9, 100, 2];

numbers.sort();                    // [10, 100, 2, 9] — sorted as text!
numbers.sort((a, b) => a - b);     // [2, 9, 10, 100] — correct

By default JavaScript sorts by converting to text, so 100 comes before 9. Always pass a comparison function for numbers.

Questions people ask#

When should I use a for loop instead?

When you need to stop early with break, or when the logic is complicated enough that a chain becomes hard to read. Both styles are perfectly acceptable.

What is the difference between forEach and map?

forEach just runs a function for each item and returns nothing. map returns a new array. If you are not using the result, forEach is the honest choice.

Why is my array full of undefined after map?

Your callback has braces but no return. n => ({ ...n }) returns an object; n => { ... } is a block that must return explicitly.

Where to go next#

Next lessonJavaScript objects explained

Keep reading

Keep going — pick your next guide

The fastest way to improve is to read one guide, then build the thing it describes. Start with the basics, or jump straight to a project.

Ask a question or share what worked

Your email address will not be published. Required fields are marked *