Skip to content
Educora
Intermediate16 min8 / 27

Arrays and array methods

Learn to work with lists: adding and removing items, and transforming data with `map`, `filter`, `find` and `reduce`.

Check yourself
In this lesson you will learn
  • Create an array, access an item by index and change it
  • Add and remove items with push, pop, shift and unshift
  • Process data with map, filter, find and reduce

If a class has 25 students, creating 25 separate variables for their marks makes no sense. That is what an array is for — an ordered list under a single name. Posts in a social feed, items in a basket, songs in a playlist — in a program all of these are usually stored as arrays.

Creating arrays and accessing items

An array is written in square brackets with items separated by commas. As with strings, indexes start at 0 and length tells you how many items there are. You can change an item by assigning a new value to its index.

JavaScript
const fruits = ['apple', 'pear', 'pomegranate'];

console.log(fruits[0]);
console.log(fruits.length);
console.log(fruits[fruits.length - 1]);

fruits[1] = 'quince';
console.log(fruits);
▸ Expected output
apple
3
pomegranate
[ 'apple', 'quince', 'pomegranate' ]

Adding and removing items

MethodWhat it does
push(x)adds an item to the end
pop()removes the last item and returns it
unshift(x)adds an item to the start
shift()removes the first item and returns it
includes(x)is x in the array — true/false
indexOf(x)the index of x, or −1
JavaScript
const queue = ['Aysel', 'Murad'];

queue.push('Leyla');
queue.unshift('Elvin');
console.log(queue);

const last = queue.pop();
const first = queue.shift();
console.log(first, last, queue);

console.log(queue.includes('Murad'), queue.indexOf('Aysel'));
▸ Expected output
[ 'Elvin', 'Aysel', 'Murad', 'Leyla' ]
Elvin Leyla [ 'Aysel', 'Murad' ]
true 0

forEach and map

Most array methods take a function as an argument and call it for every item. forEach simply does something with each item, such as printing it. map transforms each item and builds a new array of the same length from the results. The original array stays unchanged.

JavaScript
const prices = [10, 25, 4];

prices.forEach((price, index) => {
  console.log(`${index}: ${price} AZN`);
});

const sale = prices.map((price) => price * 0.9);
const labels = prices.map((price) => `${price} AZN`);

console.log(sale);
console.log(labels);
console.log(prices);
▸ Expected output
0: 10 AZN
1: 25 AZN
2: 4 AZN
[ 9, 22.5, 3.6 ]
[ '10 AZN', '25 AZN', '4 AZN' ]
[ 10, 25, 4 ]

filter, find and reduce

  • filter builds a new array from the items for which the function returns true.
  • find returns the first item that matches, or undefined if there is none.
  • reduce boils the whole array down to one value: a sum, a maximum, a count and so on.
JavaScript
const scores = [45, 92, 78, 30, 88];

const passed = scores.filter((s) => s >= 50);
const firstHigh = scores.find((s) => s > 80);
const perfect = scores.find((s) => s === 100);
const total = scores.reduce((sum, s) => sum + s, 0);

console.log(passed);
console.log(firstHigh, perfect);
console.log('Total:', total, 'Average:', total / scores.length);
▸ Expected output
[ 92, 78, 88 ]
92 undefined
Total: 333 Average: 66.6

reduce looks tricky at first. Its function receives two values: the accumulator (sum) and the current item (s). The second argument — 0 — is the accumulator's starting value. At every step, whatever the function returns becomes the accumulator for the next step:

StepsumsReturns
104545
24592137
313778215
421530245
524588333

These methods can be chained: because each returns a new array, the next method can be called on it straight away. Below we first keep the passing scores, then add a 5-point bonus to them.

JavaScript
const scores = [45, 92, 78, 30, 88];

const bonus = scores
  .filter((s) => s >= 50)
  .map((s) => s + 5);

console.log(bonus);
console.log(scores.some((s) => s < 40));
console.log(scores.every((s) => s > 20));
▸ Expected output
[ 97, 83, 93 ]
true
true
some checks whether at least one item matches, every whether all of them do.

Sorting: sort

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

console.log([...numbers].sort());
console.log([...numbers].sort((a, b) => a - b));
console.log([...numbers].sort((a, b) => b - a));

const names = ['Murad', 'Aysel', 'Leyla'];
names.sort();
console.log(names);
▸ Expected output
[ 1, 10, 100, 9 ]
[ 1, 9, 10, 100 ]
[ 100, 10, 9, 1 ]
[ 'Aysel', 'Leyla', 'Murad' ]
[...numbers] makes a copy of the array so the original is not messed up. You will learn this syntax in the next lesson.
Interactive
Loading simulation…
Watch step by step how a sorting algorithm compares items and swaps them.
Exercise

Keep only the even numbers, multiply each by 10 and print the new array with console.log. Chain filter and map.

Exercise · JavaScript
const numbers = [1, 2, 3, 4, 5, 6];
// your code here
▸ Expected output
[ 20, 40, 60 ]

Key points

  • An array is an ordered list; indexes start at 0 and length is the number of items.
  • push/pop work at the end, unshift/shift at the start.
  • map transforms every item, filter selects items, find finds the first match.
  • reduce combines an array into one value using an accumulator.
  • To sort numbers write sort((a, b) => a - b); sort changes the original.

Check yourself

10 questions. Every correct answer earns XP.

1 / 10
Given const a = [5, 10, 15];, what is a[1]?