在JavaScript中查找二维数组中最大的子数组

时间:2016-07-10 19:13:10

标签: javascript arrays

给定一个数组我想找到最长的子数组,即

var table = [
               ["Protein",["Grilled Chicken","Lamb"]],
               ["Fats",["rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr"]],
               ["Vegatables",["Carrots","Eggs","Milks","Peppers"]]
              ];

我希望它返回["Carrots","Eggs","Milks","Peppers"]

继承我的代码

function findBiggestSubArray(array){
    var biggestArrayIndex = 0;

    for(var i=0;i<array.length;i++){
      if(i === (array.length-1)){
        //We have reached the end of the array then return the array
        console.log("Reached the End");
        return array[biggestArrayIndex];
      } else {
        if(!array[biggestArrayIndex][1].length >= array[i][1].length){
          biggestArrayIndex = i;
        }//End of Inner else block
      }//End of Outer else block
    }//End of forloop
  }

2 个答案:

答案 0 :(得分:2)

一般解决方案,找到数组结构中最大的数组:

我会用递归来做,因此可以找到最大的数组,无论如何......

<div id = "panel1" class = "panel active">
    content1<br>
    content1<br>
    content1<br>
    content1<br>
    content1<br>
    </div>

针对此特例的Oneliner

/**
 *  array -> The array to check,  
 *  biggestArray -> The most biggestArray found so far
 */
function findBiggestArray(array, biggestArray){
  biggestArray = biggestArray || [];

  if (array.length > biggestArray.length)
    biggestArray = array;

  for (var i = 0; i < array.length; i++) {
    if (array[i] instanceof Array)
      biggestArray = findBiggestArray(array[i],biggestArray)
  }

  return biggestArray;
}

var multiArray = [
  ["1", "2", ["234", "334"]],
  [1,2,3,4,5, [1,2,3,4,5,6,7,7]]
]

var biggest = findBiggestArray(multiArray)
console.log(biggest) 

// This also works!
console.log(findBiggestArray([1, [1,2,3]]))

答案 1 :(得分:1)

我会这样做(查看代码中的注释以获取解释):

&#13;
&#13;
var table = [
  ["Protein", ["Grilled Chicken", "Lamb"]],
  ["Fats", ["rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr"]],
  ["Vegatables", ["Carrots", "Eggs", "Milks", "Peppers"]]
];
function findBiggestSubArray (array) {
  // Initialise empty array.
  var bigSubArray = ["", []];
  // Loop through the given array.
  for (var i = 0; i < array.length; i++) {
    // Check if the current biggest one is bigger than the saved array.
    if (array[i][1].length > bigSubArray[1].length) {
      // If bigger, replace it with current array.
      bigSubArray = array[i];
    }
  }
  // Return the biggest sub array.
  return bigSubArray[1];
}
console.log(findBiggestSubArray(table));
&#13;
&#13;
&#13;