admin管理员组

文章数量:1331388

I am new to javascript and I don't know how to iterate array of arrays in javascript.

I have a problem where I have to find largest array from an array of array input:

Return an array consisting of the largest number from each provided sub-array. For simplicity, the provided array will contain exactly 4 sub-arrays. Remember, you can iterate through an array with a simple for loop, and access each member with array syntax arr[i]

First problem is solved by me successfully whose code I have written at the end but I am not able to solve the second input.

Problem 1 [SOLVED]

  • Input: largestOfFour( [[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39],[1000,1001, 857, 1]] );

  • Output: [1000,1001,857,1]

Problem 2 [NOT SOLVED]

  • Input: largestOfFour( [[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]]), [27,5,39,1001] );

  • Output: [27,5,39,1001]

If still not clear watch this link and tell me thats it

My Code for the first problem. (Alter my code so that second can be solved)

function largestOfFour(arr) {
  var iAmLarge = new Array();
  iAmLarge = arr[0];
  var large = iAmLarge[0];

  for(var i=0;i<iAmLarge.length;i++) {
     if(large<=iAmLarge[i] ) {
        large = iAmLarge[i];
     }     
  }
  var maxFoundAt = 0;
  for(var i=0;i<arr.length;i++){ 
    var newArray=new Array();
    newArray = arr[i];
    var max = newArray[0];
    for(var j=0;j<newArray.length;j++) {
        if(max<newArray[j] ) {
        max = newArray[j];
     }     
    }
if(max>=large) {        
        large = max;
        maxFoundAt = i;     
    }
  } 
alert( arr[maxFoundAt]);
}

largestOfFour( [[4, 9, 1, 3], [13, 35, 18, 26], [32, 35, 97, 39], [1000000, 1001, 857, 1]]);

I am new to javascript and I don't know how to iterate array of arrays in javascript.

I have a problem where I have to find largest array from an array of array input:

Return an array consisting of the largest number from each provided sub-array. For simplicity, the provided array will contain exactly 4 sub-arrays. Remember, you can iterate through an array with a simple for loop, and access each member with array syntax arr[i]

First problem is solved by me successfully whose code I have written at the end but I am not able to solve the second input.

Problem 1 [SOLVED]

  • Input: largestOfFour( [[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39],[1000,1001, 857, 1]] );

  • Output: [1000,1001,857,1]

Problem 2 [NOT SOLVED]

  • Input: largestOfFour( [[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]]), [27,5,39,1001] );

  • Output: [27,5,39,1001]

If still not clear watch this link and tell me thats it

http://freecodecamp./challenges/bonfire-return-largest-numbers-in-arrays

My Code for the first problem. (Alter my code so that second can be solved)

function largestOfFour(arr) {
  var iAmLarge = new Array();
  iAmLarge = arr[0];
  var large = iAmLarge[0];

  for(var i=0;i<iAmLarge.length;i++) {
     if(large<=iAmLarge[i] ) {
        large = iAmLarge[i];
     }     
  }
  var maxFoundAt = 0;
  for(var i=0;i<arr.length;i++){ 
    var newArray=new Array();
    newArray = arr[i];
    var max = newArray[0];
    for(var j=0;j<newArray.length;j++) {
        if(max<newArray[j] ) {
        max = newArray[j];
     }     
    }
if(max>=large) {        
        large = max;
        maxFoundAt = i;     
    }
  } 
alert( arr[maxFoundAt]);
}

largestOfFour( [[4, 9, 1, 3], [13, 35, 18, 26], [32, 35, 97, 39], [1000000, 1001, 857, 1]]);
Share Improve this question edited Sep 4, 2015 at 9:18 Harsh Sharma asked Sep 4, 2015 at 8:17 Harsh SharmaHarsh Sharma 8981 gold badge14 silver badges32 bronze badges 11
  • Are those problems homework or something like that? – EnriMR Commented Sep 4, 2015 at 8:21
  • 2 @EnriMR It does not matter, as OP showed the proper effort into solving it by himself. – axelduch Commented Sep 4, 2015 at 8:22
  • 1 Define "Largest array". (Highest number/Highest Sum/etc) – Jamiec Commented Sep 4, 2015 at 8:25
  • I have to questions, for the second problem, is the output you gave the expected output or your output? Also I'm not quite sure what you mean by largest. – axelduch Commented Sep 4, 2015 at 8:25
  • 1 According to that description your first answer is also wrong. the result for 1 should be [5,27,39,1001] - the highest number from each array – Jamiec Commented Sep 4, 2015 at 8:31
 |  Show 6 more ments

5 Answers 5

Reset to default 3

For the second problem where you want to collect the largest number from each sub-array, you can do this (working snippet):

function largestOfFour(master) {
    var result = [];
    // iterate through all arrays passed
    for (var i = 0; i < master.length; i++) {
        // master[i] is an array and can be just treated like any array
        result.push(Math.max.apply(Math, master[i]));
    }
    return result;
}

var r = largestOfFour(  [[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

// show result in snippet
document.write(JSON.stringify(r));


To explain a bit, Math.max.apply(Math, array) is a trick for finding the largest value in an array. It works like this:

Math.max() accepts as many arguments as you want to pass it. For example, you can do Math.max(1,2,3,4,5,6) and it will return 6. So, if you could pass it a whole array of arguments, then it would find the max value in the whole array.

So, how do you turn an array of values into a set of arguments to a function. Well, you can use .apply() to do that. It's a method on any function in Javascript. You can read about here on MDN. So, since Math.max() is a function, we can use Math.max.apply() to use an array of values as the arguments for Math.max(). .apply() accepts two arguments itself. The first is the this value that you want the function to have. That, it turns out is not really relevant here so we pass Math which just gives the .max() function the same this value that it would have if we called it as Math.max(). The second argument to .apply() is an array of values that we want to be the arguments to our function. For that, we just pass our array. So, we end up with:

Math.max.apply(Math, myArray);

to find the largest value in myArray. To see how this works, let's suppose that we have:

var myArray = [9,8,7,1];
var highest = Math.max.apply(Math, myArray);

That is the same as this:

var highest = Math.max(9,8,7,1);

The Math.max.apply(Math, myArray) takes the array of values in myArray and passes them as consecutive arguments to Math.max() just as if we had typed them into our code manually as arguments.

And, in both cases above, highest === 9.

You have stated (in ments, and from the link provided) the problems set is

Return an array consisting of the largest number from each provided sub-array. For simplicity, the provided array will contain exactly 4 sub-arrays. Remember, you can iterate through an array with a simple for loop, and access each member with array syntax arr[i]

Which means that what you need to do is iterate each array and find the highest number from each array and return an array containing the highest number from each sub array. Therefore an input of:

 [[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39],[1000,1001, 857, 1]]

Should yield a response of

[5,27,39,1001]

In order to achieve anything in programming you should break a plex problem down into one or more simpler problems - this often results in writing a function to perform a small unit of functionality.

Start with a simple 1-dimensional array

[4, 5, 1, 3]

And write a function to find the highest number from that array.

function getLargestFromArray(arr){
    // You can do this bit!
    // Its easy, just store zero in a variable, and iterate the array
    // if the current value is greater than the stored number
    // set the stored number to this value
    // when youve iterated all values return the currently stored highest number
}

Now, you know your original input will be an array of 4 arrays (the assignment said so!) so you can use the number 4 to iterate the input

var output = new Array();
for(var i=0;i<4;i++){
    var thisArr = input[i];
    var highest = getLargestFromArray(thisArr)
    output[i] = highest; // or output.push(highest);
}

It's that simple!

This will work for any number of subarrays, so I would change the name to maxOfSubArrays or something similar. It's similar to @Jamiec solution but uses the map function to apply the max function to each sub array, you don't need to cycle over the main array.

function largestOfFour(arrayOfArrays) {
    return arrayOfArrays.map(function (singleArray) {
        return Math.max.apply(null, singleArray);
    });
}

http://jsfiddle/bLn3k14n/

var a = [[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]];
var temp = [];
for (var i = 0; i < a.length; i++) {
  temp.push(a[i].sort(function(a, b){return b - a;})[0]);
}
console.log(temp);

The answers on here are really outdated. Use the array map function and just grab the max from each array like so.

function largestOfFour(arr) {
  return arr.map(m=>Math.max(...m));
}

largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

that function can be simplified any further using arrow syntax

const largestOfFour=a=>a.map(m=>Math.max(...m))

本文标签: Iterate array of arrays in javascriptStack Overflow