How to duplicate elements of an array in JavaScript and add them to the same array.
function duplicate(arr) {
// Write Logic here
var position,lengtharr = arr.length;
for(var i=0;i<lengtharr;++i){
arr[position] = arr[i];
position++;
}
return arr;
}
var arr=[1,2];
console.log(duplicate(arr));
Please explain why the above code is not working. I'm getting "Incorrect Output" as error.
Also, I've come up with another way as shown below. But I'd like to know what's wrong with this approach.
function duplicate(arr) {
// Write Logic here
var lengtharr = arr.length;
for(var i=0;i<lengtharr;++i){
arr.push(arr[i]);
}
return arr;
}
var arr=[1,2];
console.log(duplicate(arr));
Thank you