数组替换javascript

时间:2017-11-24 14:18:47

标签: javascript jquery arrays

我有两个阵列:

  

array1 = [35,433];
array2 = [70,154,73];

需要阵列:

  

结果[0] = [35,70];
结果[1] = [35,154];
结果[2] =   [35,73];
结果[3] = [433,70];
结果[4] = [433,154];
  结果[5] = [433,73];

我的代码:

var groupAttribute = [];
    groupAttribute[0] = ['35'=>'bla','433'=>'blu'];
    groupAttribute[1] = ['70'=>'fre','154'=>'nuy','73'=>'tres'];
var counter = 0;
var countAttributes = 5;
var combinat = [];
for (var i = 0, j = 0;; j++) {
    if (i >= groupAttribute.length && j >= countAttributes) {
    	break;
    }
    if (i >= groupAttribute.length) {
    	i = 0;
    }
  	combinat[counter] = [];
    $.each(groupAttribute[i],function(key, attribute) {		
    	combinat[counter].push(parseInt(key));
    	counter++;
    	i++;
    });
	           
}
console.log(combinat);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>

请帮助我

2 个答案:

答案 0 :(得分:1)

两个分开的数组

var array1 = [35,433];
var array2 = [70,154,73];

var newArr = [];

array1.forEach(function(a) {
  array2.forEach(function(b) {
    newArr.push([a, b])
  })
})

console.log(newArr)

如果嵌套深度未知:

var arr = [[35,433], [70,154,73], [5,1]];

function Permute(arr) {
  if (arr.length === 1) {
    return arr[0];
  }
  
  var res = [];
  var sliced = Permute(arr.slice(1));
  
  arr[0].forEach(function(a) {
    sliced.forEach(function(b) {
      res.push([a].concat(b))
    })
  })
 
  return res;
}

var newArr = Permute(arr);
console.log(newArr)

希望这有帮助

答案 1 :(得分:0)

这是一个纯函数/递归解决方案,适用于任何正数的数组。

&#13;
&#13;
let array1 = [35, 433];
let array2 = [70, 154, 73];
let array3 = [1, 2, 3];

let result = combine(array1, array2, array3 /* more arrays */ );

function combine(arr, ...rest) {
    if (!rest.length) return arr.map(n => [n]);

    const sub = combine(...rest);
    return arr.reduce((a, n) => [...a, ...sub.map(a2 => [n, ...a2])], [])
}

console.log(result);
&#13;
&#13;
&#13;

对于您在评论中询问的矩阵差异,请执行以下操作:

&#13;
&#13;
var arr1 = [[35,70],[433,70],[35,73],[433,73],[35,154],[433,154]];
var arr2 = [[433,70],[433,154],[433,73],[35,154]];

var result = [
  ...aNotInB(arr1, arr2),
  ...aNotInB(arr2, arr1),
];

function aNotInB(a, b) {
  return a.filter(([x, y]) => 
    !b.some(([x2, y2]) => x == x2 && y == y2)
  )
}

console.log(result);
&#13;
&#13;
&#13;