Saurabh
Saurabh

Reputation: 159

Why pushing array into another array merges the elements instead of putting them in separate array

I have a array into which I push new values iteratively, at the end of each iteration I want the array formed to be inserted into new array. Ex: if at the end of first iteration array=[1,2,3,4], then bigarray=[[1,2,3,4]]. After 2nd iteration, if array=[5,6,7,8], then bigarray=[[1,2,3,4],[5,6,7,8]] and so on.

So basically bigarray is to contain a list of arrays out of which I can obtain arrays. ex: bigarray[0] should give me a array [1,2,3,4]

What I am doing now is array.push(some values) and at the end bigarray.push(array). Doing this merges all the values into a single array like this bigarray=[1,2,3,4,5,6,7,8] out of which I can separate first array and second array.

piece of code:

            var array=[];


            for(var i=0; i<range;i++){
                var arraychart=[];
                var jan= resp.ChartDataList[i].jan;
                arraychart.push(jan);
                var feb= resp.ChartDataList[i].feb;
                arraychart.push(feb);
                var mar= resp.ChartDataList[i].mar;
                arraychart.push(mar);
                var apr= resp.ChartDataList[i].apr;
                arraychart.push(apr);
                var may= resp.ChartDataList[i].may;
                arraychart.push(may);
                var jun= resp.ChartDataList[i].jun;
                arraychart.push(jun);
                //var jan= resp.ChartDataList[i].jan;
                array.push(arraychart);
                alert (arraychart);

            }
            alert(array);

How do I achieve the above desired result??

Upvotes: 0

Views: 126

Answers (2)

Mohamed Shaaban
Mohamed Shaaban

Reputation: 1169

You should call array.push in this way (array.push([1,2,3])) instead of (array.push(1,2,3))

var bigarray = [];

bigarray.push( [1,2,3,4] );
bigarray.push( [5,6,7,8] );

console.log(bigarray); // prints [[1,2,3,4],[5,6,7,8]]

EDIT

After seeing your code, you don't have problems in your code, just print the array using console.log instead of alert, because alert will call .toString() of the big array, and flatten it

Upvotes: 1

betmakh
betmakh

Reputation: 435

U can try something like this

bigArrray[bigArray.length] = subArray

But...

bigArrray.push([1,2,3])

...works as well for me

Upvotes: 0

Related Questions