Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - clone array inside itself

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?

like image 264
Alexandra Vorobyova Avatar asked Sep 06 '13 08:09

Alexandra Vorobyova


2 Answers

You 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]
like image 88
Frédéric Hamidi Avatar answered Sep 28 '22 20:09

Frédéric Hamidi


const arr = [0, 1, 2]
const combinedOne = [ ...arr, ...arr]

With es6, we can use the spread operator.

like image 24
Tanapruk Tangphianphan Avatar answered Sep 28 '22 18:09

Tanapruk Tangphianphan