0

Please help, I don't know what's wrong in my code. I'd like to make a function which duplicates array like: fuction duplicate([1,2,3,4] answer: [1,2,3,4,1,2,3,4].

var arr1 = [];

function duplicate(arr){
   arr1 = arr;
   for(var i = 0;i<arr.length;i++){
      arr1.push(arr[i]);    
   }
   return arr1
}

Thanks for any help

2
  • What does your code do right now? Commented Dec 12, 2017 at 21:23
  • 1
    why not use Array#concat? Commented Dec 12, 2017 at 21:23

2 Answers 2

5

You can't iterate an array while using it's length as the loop condition, and add to it's end, because you'll get an infinite loop.

Slice the array to clone it, then iterate the original, and push to the clone:

function duplicate(arr){
   var temp = arr.slice();
   
   for(var i = 0;i<arr.length;i++){
      temp.push(arr[i]);    
   }
   return temp;
}

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

An easier solution would be to Array#concat the array to itself:

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

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

Sign up to request clarification or add additional context in comments.

1 Comment

Or even return [...arr, ...arr];
1

The array is being passed in by reference, which means that just declaring another variable to point at it will still point to the same array. And then when you loop through it, you never satisfy the condition i < arr.length, because the length keeps expanding as you add to it.

You should capture the length of the array before starting your loop.

Or use one of the other answers that takes a different approach.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.