skip to Main Content

I need to create this data structure in Javascript:

var bar_data = {
  data: [
    [sistOper[0], tot[0]],
    [sistOper[1], tot[1]],
    [sistOper[2], tot[2],
    [sistOper[3], tot[3]]
  ],
  color: '#3c8dbc'
}

It works correctly, but if I have an array with 20 elements this syntax is very inefficient.

I’ve tried this, but doesn’t work:

var bar_data = {
  data: [[ sistOper, tot ]],
  color: '#3c8dbc'
}

Any suggestions?

2

Answers


  1. You can use Javascript’s hacky-looking zipping:

    const zippedData = sistOper.map((elem, i) => [elem, tot[i]]);
    

    Or, if you’re already using lodash, you can use _.zip.

    "Zipping" is the term you’re looking for though.

    Login or Signup to reply.
  2. Use a for loop to construct the data array:

    var bar_data = {        
      data: [],
      color: '#3c8dbc'
    }
    for (var i = 0; i < sistOper.length; i++)
      bar_data.data.push([sistOper[i], tot[i]]);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search