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?
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)
array.push function gathers any number of arguments with rest parameters, however i get a list of arguments from an array with spread operatorrest is when one collects multiple elements while destrucutring and in function argumentsIf 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)