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?

5 Answers 5

9

You can use Array.prototype.concat()

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

Sign up to request clarification or add additional context in comments.

3 Comments

Perfect. Just didn't know what to call it in my searches. Thanks!
@adiga thanks I didn't know how to do it without jsfiddle or something like that :)
5

You can use spread syntax

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

3 Comments

@MaheerAli i kinda make a use of both, array.push function gathers any number of arguments with rest parameters, however i get a list of arguments from an array with spread operator
@MaheerAli this is spread syntax. rest is when one collects multiple elements while destrucutring and in function arguments
@adiga thanks for info. I misunderstood a little bit
3

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

Comments

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)

Comments

0

Here's a variant with reduce

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

Comments

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.