2.2 KiB
2.2 KiB
id, title, challengeType, forumTopicId
id | title | challengeType | forumTopicId |
---|---|---|---|
587d7b89367417b2b2512b48 | Use the Spread Operator to Evaluate Arrays In-Place | 1 | 301222 |
Description
apply()
to compute the maximum value in an array:
var arr = [6, 89, 3, 45];
var maximus = Math.max.apply(null, arr); // returns 89
We had to use Math.max.apply(null, arr)
because Math.max(arr)
returns NaN
. Math.max()
expects comma-separated arguments, but not an array.
The spread operator makes this syntax much better to read and maintain.
const arr = [6, 89, 3, 45];
const maximus = Math.max(...arr); // returns 89
...arr
returns an unpacked array. In other words, it spreads the array.
However, the spread operator only works in-place, like in an argument to a function or in an array literal. The following code will not work:
const spreaded = ...arr; // will throw a syntax error
Instructions
arr1
into another array arr2
using the spread operator.
Tests
tests:
- text: <code>arr2</code> should be correct copy of <code>arr1</code>.
testString: assert(arr2.every((v, i) => v === arr1[i]) && arr2.length);
- text: <code>...</code> spread operator should be used to duplicate <code>arr1</code>.
testString: assert(code.match(/Array\(\s*\.\.\.arr1\s*\)|\[\s*\.\.\.arr1\s*\]/));
- text: <code>arr2</code> should remain unchanged when <code>arr1</code> is changed.
testString: assert((arr1, arr2) => {arr1.push('JUN'); return arr2.length < arr1.length});
Challenge Seed
const arr1 = ['JAN', 'FEB', 'MAR', 'APR', 'MAY'];
let arr2;
arr2 = []; // Change this line
console.log(arr2);
Solution
const arr1 = ['JAN', 'FEB', 'MAR', 'APR', 'MAY'];
let arr2;
arr2 = [...arr1];