- Create an array, access an item by index and change it
- Add and remove items with
push,pop,shiftandunshift - Process data with
map,filter,findandreduce
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.
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
| Method | What 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 |
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.
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
filterbuilds a new array from the items for which the function returnstrue.findreturns the first item that matches, orundefinedif there is none.reduceboils the whole array down to one value: a sum, a maximum, a count and so on.
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:
| Step | sum | s | Returns |
|---|---|---|---|
| 1 | 0 | 45 | 45 |
| 2 | 45 | 92 | 137 |
| 3 | 137 | 78 | 215 |
| 4 | 215 | 30 | 245 |
| 5 | 245 | 88 | 333 |
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.
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
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.Keep only the even numbers, multiply each by 10 and print the new array with console.log. Chain filter and map.
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
lengthis the number of items. push/popwork at the end,unshift/shiftat the start.maptransforms every item,filterselects items,findfinds the first match.reducecombines an array into one value using an accumulator.- To sort numbers write
sort((a, b) => a - b);sortchanges the original.
Check yourself
10 questions. Every correct answer earns XP.
const a = [5, 10, 15];, what is a[1]?