Repeat array in javascript

August 30, 2011 Javascript Snippet
This little snippet is useful if you want to extend an array in javascript with posts by repeating the content of the original array.

For instance, your array contains "a", "b", "c". You wish to build an array of 8 posts repeating the initial values. This function would then return a new array containing "a", "b", "c", "a", "b", "c", "a", "b".
<script type="text/javascript">
      

function repeatArray(arr, count) {
var ln = arr.length;
var b = new Array();
for(i=0; i<count; i++) {
b.push(arr[i%ln]);
}

return b;
}

</script>
And a little test bed:
var a = new Array();
      

a.push("test1");
a.push("test2");
a.push("test3");

var b = repeatArray(a, 13);

alert(b.length);

Related posts: