Oscar Godson
Oscar Godson

Reputation: 32726

Most performant way to create a JavaScript collection with generated IDs

I need to create a object like this:

{
  columns: ["Foo", "Bar", "Baz"],
  rows: {
    0: [0,1,2],
    1: [3,4,5],
  },
  cells: {
    0: "First Cell, First Row",
    1: "Second Cell, First Row",
    2: "Third Cell, First Row",
    3: "First Cell, Second Row",
    4: "Second Cell, Second Row",
    5: "Third Cell, Second Row"
  }
}

Where the numeric object keys are the row IDs and cell IDs. Creating the object itself isn't hard, but the part where I create the rows' arrays seems overly complex with what I'm doing.

Right now I'm doing, for each row, for each column, push cellId++ like this

  var cellId = 0;
  data.rows.forEach(function (row, rowId) {
    newData.rows[rowId] = [];
    data.columns.forEach(function (column, columnId) {
      newData.rows[rowId].push(cellId++);
    });
  });

What I'd love is something like (in pseudo code)

  data.rows.forEach(function (row, rowId) {
    newData.rows[rowId] = new Array({startAt: 0, endAt: 2});
  });

Is there anyway to do this?

Upvotes: 0

Views: 32

Answers (1)

user663031
user663031

Reputation:

map should help you:

var cellId = 0;
  data.rows.forEach(function (row, rowId) {
    newData.rows[rowId] = data.columns.map(function() { return cellId++; });
  });

Or use it for both dimensions:

newData = data.rows.map(function() {
  return data.columns.map(function() { 
    return cellId++;
  });
})

Upvotes: 1

Related Questions