How to duplicate every index of an array with Javascript?
I'm struggling with this because all search engine results are about find duplicates in array. And I want exactly the opposite.
I have an array of colors:
const colors = ["#fff", "#666", "#000"];
How do I simply duplicate or triplicate every one of its indexes?
x2: ["#fff", "#fff", "#666", "#666", "#000", "#000"];
x3: ["#fff", "#fff", "#fff", "#666", "#666", "#666", "#000", "#000", "#000"];
x...
Edit:
After o lot of negative votes I was compelled to say that I'm not a JS developer. I appreciate all the answers and effort. Thanks SO community.
Solution 1:
For the general case, you can use the array constructor with fill
and flatMap
:
console.log(['abc', 123, 'xyz'].flatMap(el => Array(3).fill(el)));
Solution 2:
You may have trouble finding the answer to your question because technically you want to duplicate the values at each index, not the indices themselves.
One way to do this is to build an array with every element being an array with 2 items in it, then flatten the whole thing. As in build: [["#fff", "#fff"], ["#666", "#666"]]
and then call .flat()
on it to flatten it. Most functional languages, including Javascript, provide a flatMap()
function to do just that:
["#fff", "#666", "#000"].flatMap(el => [el, el])
You can triple the elements by building a bigger innner array:
["#fff", "#666", "#000"].flatMap(el => [el, el, el])
Solution 3:
I've made more general function called duplicate
takes two arguments one arr the array we want to iterate and the other is times number of times you want duplicate each value
Using flatmap()
with Array#fill
function duplicate(arr, times){
return arr.flatMap(x=>Array(times).fill(x))
}
const colors = ["#fff", "#666", "#000"];
console.log("x2", duplicate(colors,2))
console.log("x2", duplicate(colors,3))