Chaining Methods
When you print an array, you see it the way it's written in code, with square brackets and quotes. To turn it into ordinary text, use join(). It joins all the elements into one text and puts the text you give it between them:
const names = ["Ella", "Leo", "Gina"];
console.log(names.join(", "));
console.log(names.join(" and "));
console.log(names.join());Ella, Leo, Gina
Ella and Leo and Gina
Ella,Leo,GinaWithout an argument, join() puts just a comma between the elements, with no space.
filter() and map() return arrays, and every array has these methods. So you can call the next method right on the result, without storing it in a variable first. This is called chaining:
const youngNames = animals
.filter((animal) => animal.age < 5)
.map((animal) => animal.name);
console.log(youngNames.join(", "));Gina, PipRead the chain from top to bottom: take the animals, keep those younger than 5 and make an array of their names. It's the same as two steps with a variable in between:
const young = animals.filter((animal) => animal.age < 5);
const youngNames = young.map((animal) => animal.name);Writing each method on a line of its own, starting with the dot, makes a chain easier to read. It's still one statement, though, so the semicolon goes only at the very end. join() can be the last link of a chain too: animals.map((animal) => animal.name).join(", "). It returns a text, not an array, so it has to come last.
Typical mistakes:
- The wrong order. In
animals.map((animal) => animal.name).filter((animal) => animal.age < 5),map()goes first and leaves only the names. A name is a text and has noage, so the condition is never true and the result is[]. First pick the elements, then convert them. - A semicolon in the middle of a chain. After
.filter(...);, the statement ends, and the next line, which starts with a dot, is an error:SyntaxError: Unexpected token '.'.
Instructions
Print the temperatures of the whole week on one line, separated by commas: Temperatures: 18, 23, 25, 19, 22, 16, 21. Use map() and join().
Below, print the names of the days when it was warmer than 20 degrees, with a chain of filter(), map() and join(): Warm days: Tuesday, Wednesday, Friday, Sunday.