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]
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.
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.
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.
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]); }, []);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With