在javascript中迭代数组数组

时间:2022-11-14 20:20:53

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

我是javascript的新手,我不知道如何在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]

返回一个数组,该数组由每个提供的子数组中的最大数字组成。为简单起见,提供的数组将包含4个子数组。请记住,您可以使用简单的for循环遍历数组,并使用数组语法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]

问题1 [求助]

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

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

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

    产量:[1000,1001,857,1]

Problem 2 [NOT SOLVED]

问题2 [未解决]

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

    输入: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]

    产出:[27,5,39,1001]

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

如果仍然不清楚看到这个链接并告诉我这就是它

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

http://freecodecamp.com/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]]);

5 个解决方案

#1


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.apply(Math,array)是一个用于查找数组中最大值的技巧。它的工作原理如下:

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.

Math.max()接受您想要传递的参数。例如,您可以执行Math.max(1,2,3,4,5,6),它将返回6.因此,如果您可以传递一个完整的参数数组,那么它将找到最大值整个阵列。

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:

那么,如何将一个值数组转换为函数的一组参数。好吧,你可以使用.apply()来做到这一点。它是Javascript中任何函数的一种方法。您可以在MDN上阅读此处。因此,由于Math.max()是一个函数,我们可以使用Math.max.apply()来使用一个值数组作为Math.max()的参数。 .apply()本身接受两个参数。第一个是您希望函数具有的此值。事实证明,这并不是真正相关的,所以我们传递Math,它只是给.max()函数提供了与我们称之为Math.max()时相同的值。 .apply()的第二个参数是一个值数组,我们希望它们是函数的参数。为此,我们只传递我们的数组。所以,我们最终得到:

Math.max.apply(Math, myArray);

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

找到myArray中的最大值。为了了解这是如何工作的,我们假设我们有:

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.

Math.max.apply(Math,myArray)获取myArray中的值数组,并将它们作为连续参数传递给Math.max(),就好像我们将它们作为参数手动输入到我们的代码中一样。

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

并且,在上述两种情况下,最高=== 9。

#2


2  

You have stated (in comments, 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]

返回一个数组,该数组由每个提供的子数组中的最大数字组成。为简单起见,提供的数组将包含4个子数组。请记住,您可以使用简单的for循环遍历数组,并使用数组语法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 complex 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

从一个简单的1维数组开始

[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

现在,您知道您的原始输入将是一个包含4个数组的数组(赋值如此!)因此您可以使用数字4来迭代输入

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!

就这么简单!

#3


1  

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

#4


1  

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.

这适用于任意数量的子数组,因此我将名称更改为maxOfSubArrays或类似的名称。它与@Jamiec解决方案类似,但使用map函数将max函数应用于每个子数组,您不需要在主数组上循环。

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

http://jsfiddle.net/bLn3k14n/

http://jsfiddle.net/bLn3k14n/

#5


0  

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

#1


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.apply(Math,array)是一个用于查找数组中最大值的技巧。它的工作原理如下:

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.

Math.max()接受您想要传递的参数。例如,您可以执行Math.max(1,2,3,4,5,6),它将返回6.因此,如果您可以传递一个完整的参数数组,那么它将找到最大值整个阵列。

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:

那么,如何将一个值数组转换为函数的一组参数。好吧,你可以使用.apply()来做到这一点。它是Javascript中任何函数的一种方法。您可以在MDN上阅读此处。因此,由于Math.max()是一个函数,我们可以使用Math.max.apply()来使用一个值数组作为Math.max()的参数。 .apply()本身接受两个参数。第一个是您希望函数具有的此值。事实证明,这并不是真正相关的,所以我们传递Math,它只是给.max()函数提供了与我们称之为Math.max()时相同的值。 .apply()的第二个参数是一个值数组,我们希望它们是函数的参数。为此,我们只传递我们的数组。所以,我们最终得到:

Math.max.apply(Math, myArray);

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

找到myArray中的最大值。为了了解这是如何工作的,我们假设我们有:

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.

Math.max.apply(Math,myArray)获取myArray中的值数组,并将它们作为连续参数传递给Math.max(),就好像我们将它们作为参数手动输入到我们的代码中一样。

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

并且,在上述两种情况下,最高=== 9。

#2


2  

You have stated (in comments, 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]

返回一个数组,该数组由每个提供的子数组中的最大数字组成。为简单起见,提供的数组将包含4个子数组。请记住,您可以使用简单的for循环遍历数组,并使用数组语法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 complex 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

从一个简单的1维数组开始

[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

现在,您知道您的原始输入将是一个包含4个数组的数组(赋值如此!)因此您可以使用数字4来迭代输入

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!

就这么简单!

#3


1  

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

#4


1  

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.

这适用于任意数量的子数组,因此我将名称更改为maxOfSubArrays或类似的名称。它与@Jamiec解决方案类似,但使用map函数将max函数应用于每个子数组,您不需要在主数组上循环。

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

http://jsfiddle.net/bLn3k14n/

http://jsfiddle.net/bLn3k14n/

#5


0  

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