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?

5 Answers 5

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]
Sign up to request clarification or add additional context in comments.

Comments

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

With es6, we can use the spread operator.

Comments

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"]
//

1 Comment

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.
0

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

let arrayA = [0, 1, 2];
arr = [].concat(arr, arr);
console.log(arr);

Comments

-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);

1 Comment

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]

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.