how to unpack the values of one array into the specific index of another array?

- QUESTION -

I have the following code in order to create a simple machine language array of commands.
// to ensure consistency, initialize an array of values.
var cmd = _.chunk(_.range(0, 300, 0), 30);

_.each(doses, function (dose, index) {
  // these are "headers" to the machine language instructions.
  cmd[index][0] = 1;
  cmd[index][1] = dose.number;

  // this generates the 28 commands to be executed.
  // every four blocks together represents a single command
  var commands = _.flatten(_.map(_.chunk(_.range(0, 28, 0), 4), function (day) {
    _.each(dose.wellIndexes, function (well) {
      day[well] = dose.count.value;
    });
    return day;
  }));
});
(Still WIP code).
With this commands array, I want to unpack it's values into cmd[index][2], such that it will fill the remainder of the array. Is this possible?
Looking at the docs, I have found merging two arrays, but this does not replace the values after an index, only appends to the array.
How do you unpack array values into another array in javascript?

- ANSWER -

If I understand your question correctly, a simple mix of splice, concat and apply should do the trick:
Array.prototype.splice.apply(cmd[index], [2, commands.length].concat(commands));
That is, if you need to keep some data at the end of your cmd[index] array. (in other word, your commands array is shorter than the rest of cmd[index] starting from index 2) If that is not a concern, then just splice the array and concatenate your commands to it.

0 comments:

Post a Comment

Powered by Blogger.