Javascript - clone array inside itself
Asked Answered
V

5

8

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?

Vociferate answered 6/9, 2013 at 8:31 Comment(0)
R
11

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]
Riegel answered 6/9, 2013 at 8:34 Comment(0)
B
5
const arr = [0, 1, 2]
const combinedOne = [ ...arr, ...arr]

With es6, we can use the spread operator.

Burlie answered 12/4, 2019 at 17:44 Comment(0)
D
0
// 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"]
//
Diedrediefenbaker answered 6/9, 2013 at 9:51 Comment(1)
I'm years late, but thanks for answering. However, it should be noted that it's generally bad practice to mess with a native JS class's prototype. Also note the OP's comment on Joon's answer, which explains how a similar method can lead to another property(s) being included in the end result.Heaton
T
0

Alternatively, you can also write the concat method, in this way:

let arrayA = [0, 1, 2];
arr = [].concat(arr, arr);
console.log(arr);
Torque answered 12/6, 2023 at 19:1 Comment(0)
C
-1

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);
Coaly answered 6/9, 2013 at 9:22 Comment(1)
Thanks for answer. The thing's that in my task I need to add function clone to my array's prototype. And when I try to push array into itself this function clone's added too. So I get something like that [0, 1, 2, 0, 1, 2, foo: function]Vociferate

© 2022 - 2024 — McMap. All rights reserved.