最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to duplicate a JavaScript array within itself? - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share asked Mar 22, 2019 at 15:26 nwhaughtnwhaught 1,6121 gold badge19 silver badges40 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 9

You can use Array.prototype.concat()

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

You can use spread syntax

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

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

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)

Here's a variant with reduce

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

评论列表(0)

  1. 暂无评论