DEV Community

Dan-Vy Le
Dan-Vy Le

Posted on

MJSQ 101: .concat()

More JavaScript Questions 101(MJSQ 101):

Continuing from my original blog post, I give you more javascript 101 questions answered!:

Let's tackle another easy quick algorithm question this week:

Make this work: duplicate([1,2,3,4,5]); // [1,2,3,4,5,1,2,3,4,5]]

The solution:


function duplicate(arr) {
    return arr.concat(arr)
}

console.log(duplicate([1, 2, 3, 4, 5]))

//output: [1, 2, 3, 4, 5, 1, 2, 3, 4, 5]

What do we know:

It looks like the input is [1,2,3,4,5] and the desired output is [1,2,3,4,5,1,2,3,4,5].
It also looks like it's calling a function duplicate() to make this work.
We also know of a quick array method that can add one array onto another, it's called concat()

Here's an example:


var arr = [8, 6, 7]
arr.concat[5, 3, 0, 9]

//output: [8, 6, 7, 5, 3, 0, 9]

Pseudocode:

  • So we would need to write the function
  • and call it duplicate(arr)
  • so that it could take an argument, such as an array of [1, 2, 3, 4, 5]
  • and work with the concat() array method to add the original array to itself.
  • We would then return arr.concat(arr)
  • so that when we display the output or `console.log()the function,
  • the output will give you the input twice in a new array: [1,2,3,4,5,1,2,3,4,5]

Here's the solution again in case you are one of those models that can only scroll down.

`js

function duplicate(arr) {
return arr.concat(arr)
}

console.log(duplicate([1, 2, 3, 4, 5]))

//output: [1, 2, 3, 4, 5, 1, 2, 3, 4, 5]

`

That's all for today, please leave any comments/questions/corrections in the comments. Thanks!

Sources:

Huge huge thanks to github user: yangshun for aggregating the most popular JS, CSS and HTML questions and giving us his answers to it. My weekly blog posts are to go over several questions at a time to reinforce my knowledge of fundamental javascript as I grow my expertise in it. Many of my blog will be paraphrasing if not direct quotes from his github. Find his tech interview handbook here and please support him!

And an additional thank you to Flatiron alum: Marissa O. who is a badass developer at Forbes magazine for directing me to his blog!

Top comments (0)