how to duplicate the array values in javascript

Viewed 26

input
var key=[ 'id', 'name', 'health', 'status', 'environment', 'serviceType' ]

I am expecting the below output(duplication of the values)

[ 'id', 'name', 'health', 'status', 'environment', 'serviceType', 'id', 'name', 'health', 'status', 'environment', 'serviceType' ]

2 Answers

Using the spread-operator:

const key = [ 'id', 'name', 'health', 'status', 'environment', 'serviceType' ]

const res = [...key, ...key];

console.log(res);

Using Array#concat:

const key = [ 'id', 'name', 'health', 'status', 'environment', 'serviceType' ]

const res = key.concat(key);

console.log(res);

Try to make with for as a solution

for(let i=0; i<key.length; i++){
   key.push(key);
}
Related