nwhaught
nwhaught

Reputation: 1592

How to duplicate a JavaScript array within itself?

Say I've got an array:

[1,2,3]

And I want an array:

[1,2,3,1,2,3]

Is there a way to do that without looping through the array and pushing each element?

Upvotes: 0

Views: 209

Answers (5)

Krzysztof Krzeszewski
Krzysztof Krzeszewski

Reputation: 6714

You can use spread syntax

let array = [1,2,3];
array.push(...array);
console.log(array)

Upvotes: 5

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

Here's with ES6 way of using concat:

let array1 = [1,2,3]
array1 = [...array1, ...array1]
console.log(array1)

And here's for number of length you desire for:

let array1 = [1,2,3];
let ln = array1.length;
let times = ln * 2;
array1 = Array.from({length:times}, (e, i)=>array1[i%ln])
console.log(array1)

This will allow you to stop at certain length if you wish. For eg.:

// result: [1,2,3,1,2]
let array1 = [1,2,3];
let ln = array1.length;
let times = ln * 2 - 1;
array1 = Array.from({length:times}, (e, i)=>array1[i%ln])
console.log(array1)

Upvotes: 2

adiga
adiga

Reputation: 35222

If you want to duplicate the array n times, you could use Array.from() and flatMap like this:

let duplicate = (arr, n) => Array.from({length: n}).flatMap(a => arr)

console.log(duplicate([1,2,3], 2))

Upvotes: 3

Radu Diță
Radu Diță

Reputation: 14171

Here's a variant with reduce

[1, 2, 3].reduce( (acc, item, index, arr) => { acc[index] = acc[index+arr.length] = item; return acc}, [] )

Upvotes: 0

Antoine Gautrain
Antoine Gautrain

Reputation: 421

You can use Array.prototype.concat()

let array1 = [1,2,3]
console.log(array1.concat(array1))

Upvotes: 9

Related Questions