1

How in javascript make a function for array, which will work like this:

const a = [1, 2, 3, 4, 5];
a.duplicate();     // 1, 2, 3, 4, 5, 1, 2, 3, 4, 5
2
  • Array.prototype.duplicate = function () {...};, but it is not recommended to add custom properties to native prototypes. Commented Jun 6, 2018 at 6:58
  • do you like to get a new array or mutate a? Commented Jun 6, 2018 at 7:02

6 Answers 6

3

Try following, using Array.push

const a = [1, 2, 3, 4, 5];
a.push(...a);
console.log(a);

Or can add a prototype function (Mutates Original)

const a = [1, 2, 3, 4, 5];
Array.prototype.duplicate = function(){
     this.push(...this); // mutates the original array
}
a.duplicate();
console.log(a);

Or can add a prototype function (Creates New)

const a = [1, 2, 3, 4, 5];
Array.prototype.duplicate = function(){
     return [...this, ...this]; // creates new
}
console.log(a.duplicate()); // duplicated array
console.log(a); // no change

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! It's very helpful.
2

Add a new function into the Array.prototype with name duplicate.

If you want to return a new array

Array.prototype.duplicate = function () {
  return [...this, ...this];
}

const a = [1, 2, 3, 4, 5];

const b = a.duplicate();
console.log(b);

Or mutate the original one

Array.prototype.duplicate = function () {
  this.splice(0,0, ...this);
}

const a = [1, 2, 3, 4, 5];

a.duplicate();
console.log(a);

Comments

2

Or you can use [...a,...a] to get new array without modifying the original array

const a = [1, 2, 3, 4, 5];

 

Array.prototype.duplicate = function(){
     return [...this,...this]
}


console.log(a.duplicate())
console.log("Orignal", a)

In case you don't know what ... is, It's called spread syntax

Comments

1

Create a new prototype as below:

Array.prototype.duplicate = function() {
    var length = this.length;
    for (var i = 0; i < length; i++)
        this.push(this[i]);
}

Comments

0

You can use this code -

function duplicate(coll) {

    return coll.concat(coll);
}

duplicate([1, 2]);

Comments

0

You can define a function on array by adding to its prototype (as commented by Teemu).

Your requirements are not very clear, but the following will return an array as in your example:

Array.prototype.duplicate = function() {
    return this.concat(this);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.