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
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
Share Improve this question asked Dec 12, 2017 at 21:20 TymonTymon 992 silver badges8 bronze badges 2- What does your code do right now? – Jordan Rieger Commented Dec 12, 2017 at 21:23
-
1
why not use
Array#concat
? – Nina Scholz Commented Dec 12, 2017 at 21:23
2 Answers
Reset to default 5You 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]));
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.