JavaScript中两个数组的矩阵组合 [英] Matrix combinations of two arrays in javascript

查看:137
本文介绍了JavaScript中两个数组的矩阵组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数组可以说

var termRateOptionsArr = [{
    "term": 48,
    "rate": 2.99,
    "residualPercent": 0
}, {
    "term": 60,
    "rate": 1.99,
    "residualPercent": 0
}, {
    "term": 72,
    "rate": 0.99,
    "residualPercent": 0
}];

var cashDownOptionsArr = [{
    "cashdown": "2000"
}, {
    "cashdown": "4000"
}, {
    "cashdown": "6000"
}];

我想使用以下代码将这两个数组组合成矩阵组合:

I want to combine these two arrays into a matrix combination using the following code:

var cartesian = function() {

  var combos = _.reduce(arguments, function(a, b) {
    return _.flatten(_.map(a, function(x) {
      return _.map(b, function(y) {
        return x.concat([y]);
      });
    }), true);
  }, [ [] ]);

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

};

console.table( cartesian(termRateOptionsArr,cashDownOptionsArr));

合并时遇到问题,我只获得最后一个项目数组值,而不是数组中的每个项目.我认为这与某些关闭问题有关,但不确定...任何帮助都将受到赞赏.

I having issues combining I am getting only the last item array value instead of each item in the array. I think it has to do with some closure issue but not sure... Any help is appreciated..

单击此处查看plnkr

推荐答案

问题之一是_.extend()会覆盖对象的第一个参数(目标").因此:

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]);
  }));

用新合并的对象覆盖源cashDownOptionsArr数组.

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]);
  }));

带有下划线解决方案的插件

但是,由于在不使用下划线的情况下执行此操作很容易且性能更高,因此我将这两个矩阵合并在一起:

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;
};

更新的监听器

这篇关于JavaScript中两个数组的矩阵组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆