Copying with Spread
filter() and map() create new arrays, but sort() changes the array itself. Sometimes that's a problem, because the original order is lost:
const temperatures = [18, 23, 25, 19, 22];
const sorted = temperatures.sort((a, b) => a - b);
console.log(sorted);
console.log(temperatures);[18, 19, 22, 23, 25]
[18, 19, 22, 23, 25]sort() returns the array it has sorted: the same array, not a new one. sorted and temperatures are two names for one array, and you can no longer tell which day had which temperature. To keep the original, sort a copy. You make one with three dots, called spread: [...temperatures] is a new array with all the elements of temperatures in it.
const temperatures = [18, 23, 25, 19, 22];
const sorted = [...temperatures].sort((a, b) => a - b);
console.log(sorted);
console.log(temperatures);[18, 19, 22, 23, 25]
[18, 23, 25, 19, 22]Now sort() sorts only the copy. Spread can also put several arrays into one, for example the animals fed in the morning and those fed in the afternoon, and you can add more elements around them:
const morning = ["Ella", "Leo"];
const afternoon = ["Gina", "Pip"];
const fedToday = [...morning, ...afternoon, "Max"];
console.log(fedToday);["Ella", "Leo", "Gina", "Pip", "Max"]The three dots work with objects too, in curly braces. { ...leo } is a copy of the object leo, and the properties you write after it change the copy, not the original:
const leo = { name: "Leo", species: "lion", age: 6 };
const olderLeo = { ...leo, age: 7 };
console.log(olderLeo);
console.log(leo);{ name: "Leo", species: "lion", age: 7 }
{ name: "Leo", species: "lion", age: 6 }A typical mistake is to copy with =. const copy = temperatures; creates no new array, it just gives the same array a second name. So copy.sort() sorts temperatures too. The same goes for objects.
Instructions
Create a constant bothWeeks with spread: the temperatures of last week, followed by those of this week, in one array. Print it: [18, 21, 24, 19, 23, 17, 9, 25, 16, 20].
Create sorted, a sorted copy of bothWeeks, from the coldest. Then print the coldest and the warmest temperature: Coldest: 9 and Warmest: 25.
Below, print bothWeeks once more. Its temperatures must still be in the order of the days, as on the first line.