DEV Community

Randy Rivera
Randy Rivera

Posted on

Combining Two Arrays Using the concat Method

  • Concatenation means to join items end to end. JavaScript offers the concat method for both strings and arrays that work in the same way. For arrays, the method is called on one, then another array is provided as the argument to concat, which is added to the end of the first array. It returns a new array and does not mutate either of the original arrays.
  • Here's an example:
[10, 20, 30].concat([40, 50, 60]);
Enter fullscreen mode Exit fullscreen mode
  • The returned array would be [10, 20, 30, 40, 50, 60].

  • Now let's use the concat method in the nonMutatingConcat function to concatenate attach to the end of begin. The function should return the concatenated array.

function nonMutatingConcat(original, attach) {
  // Only change code below this line

  // Only change code above this line
}
var first = [1, 2, 3];
var second = [4, 5];
nonMutatingConcat(first, second);
Enter fullscreen mode Exit fullscreen mode
  • Answer:
function nonMutatingConcat(original, attach) {
  return original.concat(attach)
}

var first = [1, 2, 3];
var second = [4, 5];
console.log(nonMutatingConcat(first, second)); // willreturn  [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

Larson, Quincy, editor. “Combine Two Arrays Using the concat Method.” Https://Www.freecodecamp.org/, Class Central, 2014, twitter.com/ossia.

Top comments (0)