HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Array duplication in JavaScript

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
arrayduplicationjavascript

Problem

I want to achieve this

var arr = [1,2,3];

var duplicateArr = duplicate(arr, 2) // will be [1,2,3,1,2,3]

var duplicateArr2 = duplicate(arr, 3) // will be [1,2,3,1,2,3,1,2,3]


I have implemented it like this:



`function duplicate(arr, n) {
var len = arr.length;
if (n == 0 || n == 1) {
return arr;
}
if (n > 1) {
for (var j = 0; j



I know this may not be the efficient way to do it.

Solution

You can avoid the nested for loops by adding the entire array at the same time. (I'm also using Janos' suggestion here)

function duplicate(arr, n) {
  let result = [];
  for(let i=0; i<n; i++) {
    result.push(...arr);
  }
  return(result);
}


We need the original array unmodified, so we can keep adding it, so I'm using a new result array. This has a few benefits. Firstly it's more common to leave the input array unmodified and return a new array, and secondly it returns an empty array when n=0, which I think makes more sense.

This uses the ES6 spread syntax. If you don't want to use ES6 you can replace

result.push(...arr);


with

result = result.concat(arr);

Code Snippets

function duplicate(arr, n) {
  let result = [];
  for(let i=0; i<n; i++) {
    result.push(...arr);
  }
  return(result);
}
result.push(...arr);
result = result.concat(arr);

Context

StackExchange Code Review Q#142839, answer score: 7

Revisions (0)

No revisions yet.