freeCodeCamp/curriculum/challenges/english/02-javascript-algorithms-and-data-structures/functional-programming/add-elements-to-the-end-of-an-array-using-concat-instead-of-push.md
Oliver Eyton-Williams ee1e8abd87
feat(curriculum): restore seed + solution to Chinese (#40683)
* feat(tools): add seed/solution restore script

* chore(curriculum): remove empty sections' markers

* chore(curriculum): add seed + solution to Chinese

* chore: remove old formatter

* fix: update getChallenges

parse translated challenges separately, without reference to the source

* chore(curriculum): add dashedName to English

* chore(curriculum): add dashedName to Chinese

* refactor: remove unused challenge property 'name'

* fix: relax dashedName requirement

* fix: stray tag

Remove stray `pre` tag from challenge file.

Signed-off-by: nhcarrigan <nhcarrigan@gmail.com>

Co-authored-by: nhcarrigan <nhcarrigan@gmail.com>
2021-01-12 19:31:00 -07:00

2.0 KiB

id, title, challengeType, forumTopicId, dashedName
id title challengeType forumTopicId dashedName
587d7da9367417b2b2512b67 Add Elements to the End of an Array Using concat Instead of push 1 301226 add-elements-to-the-end-of-an-array-using-concat-instead-of-push

--description--

Functional programming is all about creating and using non-mutating functions.

The last challenge introduced the 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--

Change the nonMutatingPush function so it uses concat to add newItem to the end of original instead of push. The function should return an array.

--hints--

Your code should use the concat method.

assert(code.match(/\.concat/g));

Your code should not use the push method.

assert(!code.match(/\.?[\s\S]*?push/g));

The first array should not change.

assert(JSON.stringify(first) === JSON.stringify([1, 2, 3]));

The second array should not change.

assert(JSON.stringify(second) === JSON.stringify([4, 5]));

nonMutatingPush([1, 2, 3], [4, 5]) should return [1, 2, 3, 4, 5].

assert(
  JSON.stringify(nonMutatingPush([1, 2, 3], [4, 5])) ===
    JSON.stringify([1, 2, 3, 4, 5])
);

--seed--

--seed-contents--

function nonMutatingPush(original, newItem) {
  // Only change code below this line
  return original.push(newItem);

  // Only change code above this line
}
var first = [1, 2, 3];
var second = [4, 5];
nonMutatingPush(first, second);

--solutions--

function nonMutatingPush(original, newItem) {
  return original.concat(newItem);
}
var first = [1, 2, 3];
var second = [4, 5];
nonMutatingPush(first, second);