Skip to content

Beginner · JavaScript basics · topic 23 of 64 · 35 min

Arrays and array methods

Explanation

An array is an ordered list of values, like a list of prices or names. Each item has a position number called an index, starting at 0. Array methods such as map, filter, find and reduce let you transform and search lists in one clear line.

Making and reading arrays

javascript
const fruits = ['mango', 'banana', 'guava'];
console.log(fruits[0]);       // 'mango' (index starts at 0)
console.log(fruits.length);   // 3
console.log(fruits[fruits.length - 1]); // 'guava' (last item)
Square brackets, items separated by commas
Think of it like this: Think of a train with numbered coaches. The engine counts as coach 0, the next is coach 1, and so on. length tells you how many coaches there are, and fruits[2] means "go to coach number 2".

Adding and removing

MethodWhat it doesChanges the array?
push(x) / pop()Add / remove at the endYes
unshift(x) / shift()Add / remove at the startYes
includes(x)Is x in the list? true/falseNo
indexOf(x)Position of x, or -1No
slice(a, b)A copy of part of the listNo
splice(i, n)Remove n items at position iYes

The big four methods

These methods take a callback that runs once for each item. They return a new value and do not change the original array.

javascript
const products = [
  { name: 'Rice 5kg', price: 350 },
  { name: 'Tea 250g', price: 140 },
  { name: 'Ghee 1L', price: 620 },
];

const names = products.map((p) => p.name);            // ['Rice 5kg', 'Tea 250g', 'Ghee 1L']
const cheap = products.filter((p) => p.price < 400);  // Rice and Tea
const ghee = products.find((p) => p.name.startsWith('Ghee')); // the Ghee object
const total = products.reduce((sum, p) => sum + p.price, 0);  // 1110
map transforms, filter keeps some, find gets one, reduce combines all
  • map: same number of items, each one changed.
  • filter: fewer (or equal) items, only those that pass a test.
  • find: the first item that passes, or undefined.
  • reduce: boils the list down to one value, like a total. The 0 is the starting value.

Sorting numbers correctly

javascript
const prices = [500, 40, 1200];
console.log([...prices].sort());                // [1200, 40, 500]  wrong: sorted as text
console.log([...prices].sort((a, b) => a - b)); // [40, 500, 1200]  low to high
console.log([...prices].sort((a, b) => b - a)); // [1200, 500, 40]  high to low
Always give sort a compare function for numbers

[...prices] uses the spread operator to make a copy first, because sort changes the array it is called on.

Tip: forEach runs a function for each item but returns nothing. When you want a new array, use map or filter instead; your code will be shorter and clearer.
Careful: Arrays start at index 0, so the last index is length - 1. Reading fruits[3] in a three-item list gives undefined, a common off-by-one bug.

Watch the lesson

Arrays and array methods · 1/6

const fruits = ['mango', 'banana', 'guava'];

An array is an ordered list of values in square brackets.

Prefer a video by a teacher? Find free videos on “javascript array methods map filter reduce find tutorial” on YouTube ↗

In real life: A product listing page

A shopping site receives a list of products. It uses filter to show only items in stock, sort with (a, b) => a.price - b.price for "Price: low to high", map to turn each product into a card, and reduce to add up the prices in the cart. One list, four methods, a complete page.

Practice (0/3 done)

Task 1 · Code · Javascript

Write a function lastItem(list) that returns the last item of an array, or undefined if the array is empty.

Task 2 · Code · Javascript

Write a function cheapNames(products, limit) that returns the names of products whose price is below limit, using filter and map. Each product looks like { name: "Tea", price: 140 }.

Task 3 · Code · Javascript

Write a function cartTotal(items) that uses reduce to return the total of price x qty for all items. Each item looks like { price: 50, qty: 2 }. An empty cart totals 0.

Quick quiz

Question 1

1.What is ['a', 'b', 'c'][1]?

Question 2

2.Which method returns a new array with only the items that pass a test?

Question 3

3.What does [3, 1, 2].map((n) => n * 2) return?

Question 4

4.What does [10, 9, 100].sort() give?

Question 5

5.What does find return when nothing matches?

Read more (free)

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next: Flexbox →

← Previous: Functions