Javascript将多维数组转换为唯一的项目数组

时间:2018-05-31 15:22:36

标签: javascript arrays matrix

我试图提出一种算法,该算法将采用任何多维数组并将其转换为具有唯一项目的数组:

示例:

  var arr = [
       ["bananas", "oranges"],
       ["cars", "trucks", "airplanes"],
       ["Jim", "Bob", "David", "Diana"]
  ];

  // I need to create an array that will contain a unique record of each item in the array

  /*
  NEED TO OUTPUT TO
  newArr = [
       ["bananas", "cars", "Jim"],
       ["bananas", "cars", "Bob],
       ["bananas", "cars", "David],
       ["bananas", "cars", "Diana],
       ["bananas", "trucks", "Jim"],
       ["bananas", "trucks", "Bob],
       ["bananas", "trucks", "David],
       ["bananas", "trucks", "Diana],
       ["bananas", "airplanes", "Jim"],
       ["bananas", "airplanes", "Bob],
       ["bananas", "airplanes", "David],
       ["bananas", "airplanes", "Diana],  
       ["oranges", "cars", "Jim"],
       ["oranges", "cars", "Bob],
       ["oranges", "cars", "David],
       ["oranges", "cars", "Diana],
       ["oranges", "trucks", "Jim"],
       ["oranges", "trucks", "Bob],
       ["oranges", "trucks", "David],
       ["oranges", "trucks", "Diana],
       ["oranges", "airplanes", "Jim"],
       ["oranges", "airplanes", "Bob],
       ["oranges", "airplanes", "David],
       ["oranges", "airplanes", "Diana]
     ];
  */

以上只是一个例子。我需要这个算法来处理任何大小的数组。我根本没有走得太远。任何帮助将不胜感激。

这是我迄今为止所拥有的 - 它几乎不多而且不漂亮(仅供参考 - 如果它有帮助,我愿意使用jQuery):



function foo() {
  
  var arr = [
  ["bananas", "oranges"],
  ["cars", "trucks", "airplanes"],
  ["Jim", "Bob", "David", "Diana"]
];

  
  var i = 0, j = 0;
  
  //Define the containing array
  var newArr = [];
  
  //Used to calculate the total unique entries (24 in this example: 2 * 3 * 4)
  var totalObjects = 1;
  
  //Calculate total unique objects
  for (i = 0; i < arr.length; i++) {
    totalObjects *= arr[i].length;
  }
  
  //Identify the new array to contain 24 arrays each with 3 entries
  for (i = 0; i < totalObjects; i++) {
    newArr.push(new Array(arr.length));
  }
  
  
  for (i = 0; i < newArr.length; i++) {    
    for (j = 0; j < newArr[i].length; j++) {
      newArr[i][j] = arr[j][i];
    }    
  }
  
}

foo();
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:8)

您可以使用reduce,其中同一数组的每个项目都与其他数组的项目一起收集。然后返回结果。

var array = [["bananas", "oranges"], ["cars", "trucks", "airplanes"], ["Jim", "Bob", "David", "Diana"]],
    result = array.reduce(
        (a, b) => a.reduce((r, v) => r.concat(b.map(w => [].concat(v, w))), [])
    );
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }