* fix: convert js algorithms and data structures * fix: revert some blocks back to blockquote * fix: reverted comparison code block to blockquotes * fix: change js to json Co-Authored-By: Oliver Eyton-Williams <ojeytonwilliams@gmail.com> * fix: convert various section to triple backticks * fix: Make the formatting consistent for comparisons
2.7 KiB
2.7 KiB
id, title, challengeType
| id | title | challengeType |
|---|---|---|
| 587d7da9367417b2b2512b67 | Add Elements to the End of an Array Using concat Instead of push | 1 |
Description
concat method as a way to combine arrays into a new one without mutating the original arrays. Compare concat to the push method. Push adds an item to the end of the same array it is called on, which mutates that array. Here's an example:
var arr = [1, 2, 3];
arr.push([4, 5, 6]);
// arr is changed to [1, 2, 3, [4, 5, 6]]
// Not the functional programming way
Concat offers a way to add new items to the end of an array without any mutating side effects.
Instructions
nonMutatingPush function so it uses concat to add newItem to the end of original instead of push. The function should return an array.
Tests
tests:
- text: Your code should use the <code>concat</code> method.
testString: assert(code.match(/\.concat/g), 'Your code should use the <code>concat</code> method.');
- text: Your code should not use the <code>push</code> method.
testString: assert(!code.match(/\.push/g), 'Your code should not use the <code>push</code> method.');
- text: The <code>first</code> array should not change.
testString: assert(JSON.stringify(first) === JSON.stringify([1, 2, 3]), 'The <code>first</code> array should not change.');
- text: The <code>second</code> array should not change.
testString: assert(JSON.stringify(second) === JSON.stringify([4, 5]), 'The <code>second</code> array should not change.');
- text: <code>nonMutatingPush([1, 2, 3], [4, 5])</code> should return <code>[1, 2, 3, 4, 5]</code>.
testString: assert(JSON.stringify(nonMutatingPush([1, 2, 3], [4, 5])) === JSON.stringify([1, 2, 3, 4, 5]), '<code>nonMutatingPush([1, 2, 3], [4, 5])</code> should return <code>[1, 2, 3, 4, 5]</code>.');
Challenge Seed
function nonMutatingPush(original, newItem) {
// Add your code below this line
return original.push(newItem);
// Add your code above this line
}
var first = [1, 2, 3];
var second = [4, 5];
nonMutatingPush(first, second);
Solution
function nonMutatingPush(original, newItem) {
return original.concat(newItem);
}
var first = [1, 2, 3];
var second = [4, 5];
nonMutatingPush(first, second);