Toretto
Toretto

Reputation: 4711

How to duplicate a value of array and push it same array in javascript?

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

Answers (5)

Henrik Peinar
Henrik Peinar

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());

http://jsfiddle.net/4a8pw4u5/

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

Andy
Andy

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]

DEMO

Upvotes: 2

Adnan Ahmed
Adnan Ahmed

Reputation: 686

Here's a simple solution:

var smValue = [1,2,3];
smValue = smValue.concat(smValue);

Upvotes: 0

Chris Charles
Chris Charles

Reputation: 4446

A simple way would be to concat the array with itself:

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

Demo

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

W van Rij
W van Rij

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

Related Questions