Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to duplicate elements in a js array?

Whats the easiest way (with "native" javascript) to duplicate every element in a javascript array?

The order matters.

For example:

a = [2, 3, 1, 4] // do something with a a // a is now [2, 2, 3, 3, 1, 1, 4, 4] 
like image 390
Jan Rüegg Avatar asked Oct 23 '15 14:10

Jan Rüegg


People also ask

How do you duplicate an element in an array?

Duplicate elements can be found using two loops. The outer loop will iterate through the array from 0 to length of the array. The outer loop will select an element. The inner loop will be used to compare the selected element with the rest of the elements of the array.

How can you double elements of an array in JavaScript?

Using the has() method In the above implementation, the output array can have duplicate elements if the elements have occurred more than twice in an array. To avoid this and for us to count the number of elements duplicated, we can make use of the use() method.

Can array have duplicate values JavaScript?

To check if an array contains duplicates: Pass the array to the Set constructor and access the size property on the Set . Compare the size of the Set to the array's length. If the Set contains as many values as the array, then the array doesn't contain duplicates.


1 Answers

I came up with something similar to tymeJV's answer

[2, 3, 1, 4].reduce(function (res, current, index, array) {     return res.concat([current, current]); }, []); 
like image 171
axelduch Avatar answered Sep 16 '22 14:09

axelduch