0

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);
2
  • Well it does because I'm using mvc 4 view for this example. I put it the C# category because I figured maybe it was an issue with razor script syntax, etc. Commented Jun 29, 2015 at 21:41
  • possible duplicate of Split array into chunks Commented Jun 29, 2015 at 21:48

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Yeah, but this is how the data comes out now: dataArray.push(["1434100866", "599.0"]); dataArray.push(["1434100870", "349.0"]); dataArray.push(["1434100863", "233.0"]); dataArray.push(["1434100849", "269.0"]); dataArray.push(["1434100857", "682.0"]); dataArray.push(["1434100862", "248.0"]); dataArray.push(["1434100865", "342.0"]); dataArray.push(["1434100848", "960.0"]); dataArray.push(["1434100853", "270.0"]); dataArray.push(["1434100850", "253.0"]);
No. This is correct. It turned out that my datatypes were incorrect.
0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.