How to double array values

I have an array:

arr = ["a", "b", c"]

I want to double the values ​​e.g.

arr = ["a", "b", c", "a", "b", "c"]

(not in a specific order).

What is the best way to do this in JavaScript?

+4
source share
4 answers

Possible solution using Array#concat.

var arr = ["a", "b", "c"],
    res = arr.concat(arr);
    
    console.log(res);
Run codeHide result
+8
source

You can also use ES6 distribution syntax with Array.push:

let arr = ['a', 'b', 'c'];
arr.push(...arr);

console.log(arr);
Run codeHide result
+4
source

Array() , , fill() .

var arr = ["a", "b", "c"];

var newArr = [].concat(...Array(3).fill(arr))
console.log(newArr)
Hide result
+1

for-loop, .

var arr=["a","b","c"];
var len=arr.length;
for(var i=len;i<2*len;i++) arr[i]=arr[i-len]
console.log(arr);
Hide result
0

Source: https://habr.com/ru/post/1675461/


All Articles