Suppose I need an array with a number of repetitive elements, like this:
[3,3,3,3,3,8,8,8,8,5,5,5,5,5,5]
(so that's five 3s, four 8s, and six 5s)
In python, you can define this very elegantly like this:
[3]*5+[8]*4+[5]*6
Are there similar constructions in JS or PHP?
In this example, defining the entire array explicitly isn't that much of a problem. But if there are many elements, with lots of repetitions, this can become very tedious (not to mention prone). I want my code size to stay equal, regardless of whether the array has five 3s or five hundred.
In JS, the shortest I can think of is:
var a = [];
[[3,5],[8,4],[5,6]].forEach(function(x){while(x[1]--)a.push(x[0])});
Similar in PHP:
foreach(array(3=>5,8=>4,5=>6) as $d=>$n) while($n--) $a[]=$d;
Obviously this doesn't score bonus points for readability. Is there a better way (preferably some language construct) to do this?