How to set up this duplication function in javascript?

33 views Asked by At

This is what I need to make work in JavaScript: 

[1,2,3,4,5].duplicate(); // [1,2,3,4,5,1,2,3,4,5]

Best practices? Ideas?

1

There are 1 answers

0
Tushar On

Use concat on the same array. It'll duplicate the elements of the array.

The concat() method returns a new array comprised of the array on which it is called joined with the array(s) and/or value(s) provided as arguments.

// Define method on prototype so that it can be directly called on array
Array.prototype.duplicate = function() {
    return this.concat(this);
};