duplicate same elements in an array in javascript

Viewed 51

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.

3 Answers

try to concat, like:

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

array1 = array1.concat(array1);

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]

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