dijam dijam - 4 months ago 8
Javascript Question

Find biggest subarray in a 2d array in JavaScript

Given an array I want to find the largest sub array by the length i.e

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


I want it to return
["Carrots","Eggs","Milks","Peppers"]


Heres my code

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
}

Answer

I would do this way (see the comments in the code for explanation):

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

Comments