How to create individual objects and list them in an array using javascript?

My current array is not creating individual objects as I would like it to. My data is in the following format:

["1434100866", "599.0", "1434100870", "349.0", "1434100863", "233.0", "1434100849", "269.0", "1434100857", "682.0", "1434100862", "248.0", "1434100865", "342.0", "1434100848", "960.0", "1434100853", "270.0", "1434100850", "253.0"]

I would like my data to be in the following format:

[[item1, item2],[item1, item2],[item1, item2], ...];

Here's my code:

        var dataArray = new Array();
        @foreach (var record in Model)
        {
            @:dataArray.push("@record.date", "@record.rate");
        }        
        console.log(dataArray);

Upvotes: 0

Views: 38

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386560

var a=["1434100866", "599.0", "1434100870", "349.0", "1434100863", "233.0", "1434100849", "269.0", "1434100857", "682.0", "1434100862", "248.0", "1434100865", "342.0", "1434100848", "960.0", "1434100853", "270.0", "1434100850", "253.0"];
var b = a.reduce(function (res, el, i) {
    if (i % 2) {
        res[res.length - 1].push(el);
    } else {
        res.push([el]);
    }
    return res;
}, []);
 document.getElementById('out').innerHTML = JSON.stringify(b, null, 4);
<pre id="out"></pre>

Upvotes: 0

Amit
Amit

Reputation: 46323

You want to push a new array, not new values. Do this:

var dataArray = new Array();
@foreach (var record in Model)
{
    @:dataArray.push(["@record.date", "@record.rate"]);
}        
console.log(dataArray);

Upvotes: 2

Related Questions