Reputation: 4711
I am try to learn more about the JavaScript and I have one of the assignment where I have array and I need to duplicate that and return the result as below :
var smValue = [1,2,3];
smValue.duplicate()
will give the output like :
[1,2,3,1,2,3]
I got stuck on that. I have tried to create function like that :
var smValue = [1,2,3];
fuction duplicate (){
for(i=0;i<=smValue.length;i++){
array[smValue.length + 1] = smValue.push(smValue[i]);
}
return array;
}
smValue.duplicate();
But failed. Please help me to resolve it. It may the vary basic but I have never seen this before.
Upvotes: 0
Views: 132
Reputation: 2201
Theoretical: You loop over the array and push each key back into the array using Array.prototype.push
Practical:
var smValue = [1,2,3];
for(var i = 0, len = smValue.length;i < len;i++) {
smValue.push(smValue[i]);
}
If you want to define new function that does it on every array, you want to do this:
var myArray = [1,2,3];
Object.defineProperty(Array.prototype, 'duplicate', {
enumerable: false,
value: function duplicate() {
for(var i = 0, len = this.length;i < len;i++) {
this.push(this[i]);
}
return this;
}
});
console.log(myArray.duplicate());
I'm using Object.defineProperty to create non-enumerable property as Array.prototype.newDuplicate would add enumerable property.
And yes, you can use concat, but considering you tried to do it with a loop, I used for loop to show how to do it with that.
Upvotes: -2
Reputation: 63524
The alternative (easier?) way is to use concat
:
function duplicate(arr) {
return arr.concat(arr);
}
To add this as a method on the array prototype:
if (!('duplicate' in Array.prototype)) {
Array.prototype.duplicate = function () {
return this.concat(this);
};
}
[4, 5, 6].duplicate(); // [4, 5, 6, 4, 5, 6]
Upvotes: 2
Reputation: 686
Here's a simple solution:
var smValue = [1,2,3];
smValue = smValue.concat(smValue);
Upvotes: 0
Reputation: 4446
A simple way would be to concat the array with itself:
function duplicate (arr){
return arr.concat(arr)
}
Or if you want to call it on the array itself.
Array.prototype.duplicate = function(){
return this.concat(this)
}
smValue.duplicate() // returns [1,2,3,1,2,3]
Upvotes: 4
Reputation: 536
You can do the following:
var duplicate = smValue.concat(smValue);
Concat 'merges' array's together, or a better word is joining them together.
Upvotes: 1