0
\$\begingroup\$

This code returns an array that consists of two copies of the input array.

Can you review this algorithm?

//input: [1, 2, 3]  output: [1, 2, 3, 1, 2, 3]              
function duplicate(arr) {
 let copy = [];
 for(let i = 0; i < arr.length; i++) {
  copy.push(arr[i])
  }
 return copy.concat(arr)
 }
\$\endgroup\$
3
  • \$\begingroup\$ Just use return arr.concat(arr) \$\endgroup\$ Commented May 16, 2018 at 4:15
  • 1
    \$\begingroup\$ Or the ES6+ way return [...arr, ...arr]; \$\endgroup\$ Commented May 16, 2018 at 4:51
  • \$\begingroup\$ Javascript ... duplicate an array. A good SO thread & starting place for looking into whys and wherefores of array duplication variations. \$\endgroup\$ Commented May 22, 2018 at 17:57

1 Answer 1

3
\$\begingroup\$

The alternative approaches in the comments return arr.concat(arr); and return [...arr, ...arr]; are good replacements.

However, if you wrote this as part of a course, you should consider the following:

  • Your indentation is off, this is rule 1 in writing code: indent it
  • You are missing a semicolon after copy.push(arr[i])
  • In such a small function, I would have declared i up top in that let statement
\$\endgroup\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.