Skip to content Skip to sidebar Skip to footer

Matrix Combinations Of Two Arrays In Javascript

I have two arrays lets say var termRateOptionsArr = [{ 'term': 48, 'rate': 2.99, 'residualPercent': 0 }, { 'term': 60, 'rate': 1.99, 'residualPercent': 0 },

Solution 1:

One of the issues is that _.extend() overwrites the object in it's first parameter ("destination"). So:

return _.flatten(_.map(combos, function(item) {
    return  _.extend(item[0], item[1]);
  }));

overwrites your source cashDownOptionsArr array with newly merged objects.

One fix is to clone the destination object like this:

return _.flatten(_.map(combos, function(item) {
    var clone0 = _.clone(item[0]);
    return  _.extend(clone0, item[1]);
  }));

plunker with underscore solution

However, since it's easy and much more performant to do this without underscore, I'd combine the two matrices like this instead:

var cartesian = function(a,b) {

  var combos= [];
  var i=0;
  for (var x=0; x<a.length;x++)
     for (var y=0; y<b.length;y++)
     { 
       combos[i]={};
       // Copy properties of a[x]for (var indx in a[x]) {
          combos[i][indx] = a[x][indx];
       }
       // Copy properties of b[y]for (var indx in b[y]) {
          combos[i][indx] = b[y][indx];
       }
      i++;
     }
   return combos;
};

Updated plunker

Solution 2:

According to this post: How can I add a key/value pair to a JavaScript object?, I think you should be able to use a syntax like this:

termRateOptionsArr[i].cashdown = cashDownOptionsArr[i].cashdown;

Post a Comment for "Matrix Combinations Of Two Arrays In Javascript"