I have an array ["0", "1", "2"] and I need to create function that makes it
["0", "1","2", "0", "1", "2"]. I wrote that clone function:
arr = [0, 1, 2];
arr.clone = function() {
var b = [];
for (var i = 0; i < arr.length; i++) {
b.push(arr[i]);
}
var c = b.concat(b);
return c;
}
arr.clone();
Am I doing it right? Maybe there's a better or shorter way to clone the elements?
I have an array ["0", "1", "2"] and I need to create function that makes it
["0", "1","2", "0", "1", "2"]. I wrote that clone function:
arr = [0, 1, 2];
arr.clone = function() {
var b = [];
for (var i = 0; i < arr.length; i++) {
b.push(arr[i]);
}
var c = b.concat(b);
return c;
}
arr.clone();
Am I doing it right? Maybe there's a better or shorter way to clone the elements?
Share Improve this question asked Sep 6, 2013 at 8:31 Alexandra VorobyovaAlexandra Vorobyova 1072 silver badges7 bronze badges5 Answers
Reset to default 11You only have to use concat() by itself, since it builds a new array:
var arr = [0, 1, 2];
arr = arr.concat(arr); // [0, 1, 2, 0, 1, 2]
const arr = [0, 1, 2]
const binedOne = [ ...arr, ...arr]
With es6, we can use the spread operator.
// try this
Array.prototype.self2 = function () {
return ( Array.prototype.push.apply( this, this ), this );
};
console.log( [1,2,"a"].self2() );
//
// [1, 2, "a", 1, 2, "a"]
//
Alternatively, you can also write the concat method, in this way:
let arrayA = [0, 1, 2];
arr = [].concat(arr, arr);
console.log(arr);
Frédéric Hamidi's answer is probably the best answer if all of your target browsers support Array.concat
method, and you don't mind creating a new array.
Here's how you can keep the old array reference without creating a new array, and is fully cross-browser.
arr.push.apply(arr, arr);