I try unsuccessfully to get an array I wanted from this loop: var a = [1,2,3,4]; var b = []; for (var i = 0; i < 4; i++) { b.push(a[i]); console.log(b); // [1] // [1, 2] // [1, 2, 3] // [1, 2, 3, 4] } Code (markup): The result I wanted is: [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4] Code (markup): How do I get it? Thank you, Note: I don't want var c = a.concat(a,a,a); as data may different.
Hello, I don't exactly understand why do you want to avoid using concat, but if you do, you can achieve this result using inner loop like this: var a = [1,2,3,4]; var b = []; for (var i = 0; i < 4; i++) { for (var j = 0; j < a.length; j++) { b.push(a[j]); } console.log(b.toString()); } Code (markup): will output: "1,2,3,4" "1,2,3,4,1,2,3,4" "1,2,3,4,1,2,3,4,1,2,3,4" "1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4" Code (markup): The resulting array is created by appending items one by one.
Thank you, I do not avoid using concat but I don't want array a to repeat itself as it may different. The array is generated by another function and it is feed into this function. Here's the mock up: setInterval(function(){ var a = Math.floor((Math.random()*100)+1); x(a); },500); function x(i) { this.i = i; console.log(i); var b = []; for (var i = 0; i < 4; i++) { // pick every 4 i's that reached here and put them together } } Code (markup): I want to pick every 4 arrays from that serial to be merged together (concat) but I've no idea how to do it. Hope, I explain it clearly.
So I believe you want this: function x(input) { console.log(input); if(!this.counter) { // initialize the variables this.data = []; this.counter = 0; } // append this input to the rest this.data = this.data.concat(input); this.counter++; if(this.counter == 4) { // do something with the output output = this.data; console.log(output); // clear the data to repeat the cycle this.data = []; this.counter = 0; } } Code (markup): This will wait for 4 input arrays and put them together.