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
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
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);
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
Array.prototype.duplicate = function () {...};, but it is not recommended to add custom properties to native prototypes.a?