Endrit Shabani
Endrit Shabani

Reputation: 35

duplicate same elements in an array in javascript

I want to duplicate array with same elements that contains the first array For example, I have this array

let array1 = [{title: "test1"}, {title: "Test2"}, {title: "test3"}];

I need to transform it into

array1 = [{title: "test1"}, {title: "Test2"}, {title: "test3"}, {title: "test1"}, {title: "Test2"}, {title: "test3"}];

Thanks a lot.

Upvotes: 2

Views: 58

Answers (3)

Elias
Elias

Reputation: 155

try to concat, like:

let array1 = [{title: "test1"}, {title: "Test2"}, {title: "test3"}];

array1 = array1.concat(array1);

Upvotes: 4

Pythagus
Pythagus

Reputation: 150

You can also achieve it with a little for loop :)

let arr = [1, 2, 3] ;
let new_array = [] ;
for(let i = 0 ; i < 2 ; i++) {
    new_array = new_array.concat(arr) ;
}

console.log(new_array) ;

Upvotes: -2

Ewomazino Ukah
Ewomazino Ukah

Reputation: 2366

I am not sure what you are trying to achieve, but here's a solution.

let array1 = [{title: "test1"}, {title: "Test2"}, {title: "test3"}];  
array1 = [ ...array1, ...array1]

Upvotes: 1

Related Questions