3

I'm trying to come up with an algorithm that will take any multidimensional array and convert it to an array with unique items:

Example:

  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]
     ];
  */

The above is just an example. I need this algorithm to handle any size array. I have not got very far at all. Any help would be greatly appreciated.

Here's what I have so far - its hardly much and not pretty (FYI - I am open to using jQuery if it helps):

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();
Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44
bagofmilk
  • 1,492
  • 8
  • 34
  • 69

1 Answers1

8

You could use a reduce where each item of the same array is collected with an item of the other arrays. Then the result is returned.

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; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392