0

I've been struggling with converting the following C# code into something I can use in JavaScript:

var g = Model.List.GroupBy(r => Model.List.IndexOf(r) / 3).ToList();

It's use was to create the appropriate number of rows, with the appropriate number of columns within them. So for example if the list had 6 elements it would allow me to create 3 rows with 2 columns in it, this was all done in razor pages using the above GroupBy and the below code:

foreach (var parent in g)
{
       @Html.Raw("<div class='row'>");

       foreach (var item in parent)
       {
            // populate contents of row
       }

       @Html.Raw("</div>");
}

However for certain reasons I can't do this in Razor and need to create an alternative in JavaScript but I'm struggling to figure out a way to do this.

Primarily because I don't understand entirely how 'GroupBy' creates the list of groups and what would be a suitable alternative.

Any help, or pointing in the right direction would be great. I've tried a few solutions I found online for creating 'GroupBys' but I couldn't get them to work the way I was expecting. I also thought maybe I could split the original list into a list of dictionaries, but again had little success. I'm possibly missing something obvious.

Charlie
  • 22,886
  • 11
  • 59
  • 90
JoeTomks
  • 3,243
  • 1
  • 18
  • 42

1 Answers1

0

In the end it turns out I was just missing the obvious answer, I found this excellent SO answer. I had looked at slice but couldn't quite visualise how to use it for my problem (obviously been a long day).

The post showed this snippet:

var i,j,temparray,chunk = 10;
for (i=0,j=array.length; i<j; i+=chunk) {
    temparray = array.slice(i,i+chunk);
    // do whatever
}

In the end my JavaScript code looked something like this:

var listdata = await octokit.repos.listForUser({ "username": "", "type": "owner" });

var chunk = 2;
var loop = 0;
var tempArray = [];
for (var s = 0; s < listdata.data.length; s += chunk) {
    tempArray[loop] = listdata.data.slice(s, s + chunk);
    loop++;
}

var htmlString = "";

for (var t = 0; t < tempArray.length; t++) {

    htmlString += "<div class='row'>";
    var innerArray = tempArray[t];

    for (var r = 0; r < innerArray.length; r++) {

        var repo = innerArray[r];

        htmlString += 
         "<div class=\"col-md-6 col-sm-6 col-xs-12\">" +
            "<div>" + repocontent + "</div>" +
         "</div>"
    }

    htmlString += "</div>";
}

So with a list that's 6 items long, it gets split into an array that contains 3 lists of 2 items. Then I just create the html string using two for loops to create the outer bootstrap rows and the inner column classes. There's probably a more efficient way to do this but this worked a treat.

JoeTomks
  • 3,243
  • 1
  • 18
  • 42