Arrays
How to add and remove items in a JavaScript array, and how filter(), map() and reduce() work like Java's Stream methods.
Apprentice · JavaScript · Updated
Arrays in JavaScript function more like ArrayLists in Java. They are flexible and easy to use.
// declares an array with values
const names = ['Emma', 'Liam', 'Olivia', 'Noah', 'Ava'];
// declare an empty array
const numbers = [];
// push() adds a value to the END of the array
numbers.push(7);
numbers.push(21);
numbers.push(3);
// pop() removes a value from the END of the array
// lastNumber has the value 3
const lastNumber = numbers.pop();
// unshift() adds a value to the BEGINNING of the array
numbers.unshift(35);
// shift() removes a value from the BEGINNING of the array
// firstNumber has the value 35
const firstNumber = numbers.shift();
Array Methods and Arrow Functions
JavaScript arrays have methods such as filter(), map() and reduce() that work like Java's Stream methods. You pass each one a small function, usually written as an arrow function: n => n * 2 takes n and returns n * 2, like a Java lambda.
filter()
filter() allows you to find items that match your criteria.
const numbers = [1, 2, 3, 4];
// this returns an array of all even numbers: [2, 4]
const even = numbers.filter(n => n % 2 === 0);
map()
map() changes the shape of the items in the array.
const numbers = [1, 2, 3];
// create a new array with each number doubled: [2, 4, 6]
const doubled = numbers.map(n => n * 2);
reduce()
reduce() aggregates the values in your array. Notice that the initial value is defined as the second argument instead of the first as it is in Java.
const numbers = [1, 2, 3, 4];
// aggregate all numbers by summing them: 10
const sum = numbers.reduce(
(temp, current) => temp + current
, 0 // initial value is the 2nd argument
);
Do it: add up the busy days' sales
The snack stand writes down how many snacks it sells each day. A day that reaches the stand's target is a busy day, and the owner wants to know how many snacks were sold on the busy days, all together.
The function gets two values:
sales: the snacks sold each day, an array of numbers, such as[24, 36, 12, 48, 30].target: the count a busy day reaches, a number, such as30.
For example, busyDayTotal([24, 36, 12, 48, 30], 30):
| Day's count | At or over 30? |
|---|---|
| 24 | no |
| 36 | yes |
| 12 | no |
| 48 | yes |
| 30 | yes: reaching the target counts |
The busy days are 36, 48 and 30, and 36 + 48 + 30 = 114. The function returns 114.
Your job: write the function busyDayTotal(sales, target).
- Keep the counts that are at or over
target. - Return their sum.
- When no day reaches the target, return
0. - Leave
salesas it is: the same counts, in the same order.
Practiced live on the lesson page: write the JavaScript right there and check it.