如何找到JavaScript数组中包含的最大数字?

时间:2021-03-31 21:30:31

I have a simple JavaScript Array object containing a few numbers.

我有一个简单的JavaScript数组对象,其中包含一些数字。

[267, 306, 108]

Is there a function that would find the largest number in this array?

是否有一个函数可以找到这个数组中最大的数?

20 个解决方案

#1


289  

Resig to the rescue:

Resig救援:

Array.max = function( array ){
    return Math.max.apply( Math, array );
};

#2


182  

You can use the apply function, to call Math.max:

可以使用apply函数调用Math.max:

var array = [267, 306, 108];
var largest = Math.max.apply(Math, array); // 306

How it works?

它是如何工作的?

The apply function is used to call another function, with a given context and arguments, provided as an array. The min and max functions can take an arbitrary number of input arguments: Math.max(val1, val2, ..., valN)

apply函数用于调用另一个函数,它具有给定的上下文和参数,作为数组提供。最小和最大函数可以取任意数量的输入参数:Math。max(val1,val2,…valN)

So if we call:

所以如果我们叫:

Math.min.apply(Math, [1,2,3,4]);

The apply function will execute:

应用函数将执行:

Math.min(1,2,3,4);

Note that the first parameter, the context, is not important for these functions since they are static, they will work regardless of what is passed as the context.

注意,第一个参数上下文对这些函数来说并不重要,因为它们是静态的,不管作为上下文传递的是什么,它们都可以工作。

#3


34  

I've found that for bigger arrays (~100k elements), it actually pays to simply iterate the array with a humble for loop, performing ~30% better than Math.max.apply():

我发现,对于更大的数组(~100k元素),使用简单的for循环迭代数组实际上是有好处的,其性能比Math.max.apply()好30%:

function mymax(a)
{
    var m = -Infinity, i = 0, n = a.length;

    for (; i != n; ++i) {
        if (a[i] > m) {
            m = a[i];
        }
    }

    return m;
}

Benchmark results

基准测试结果

#4


34  

The easiest syntax, with the new spread operator:

最简单的语法,使用新的扩展操作符:

var arr = [1, 2, 3];
var max = Math.max(...arr);

Source : Mozilla MDN

来源:Mozilla MDN

#5


32  

I'm no JS expert, but I wanted to see how these methods stack up, so this was good practice for me. I don't know if this is technically the right way to performance test these, but I just ran them one right after another, as you can see in my code.

我不是JS专家,但我想看看这些方法是如何组合在一起的,所以这对我来说是很好的实践。我不知道从技术上来说,这是否是进行性能测试的正确方法,但我只是一个接一个地运行它们,正如您在我的代码中看到的那样。

Sorting and getting the 0th value is by far the worst method (and it modifies the order of your array, which may not be desirable). For the others, the difference is negligible unless you're talking millions of indices.

排序和获取第0个值是迄今为止最糟糕的方法(并且它修改了数组的顺序,这可能不可取)。对于其他的,差别是可以忽略的,除非你说的是数以百万计的指数。

Average results of five runs with a 100,000-index array of random numbers:

拥有10万索引随机数的5次运行的平均结果:

  • reduce took 4.0392ms to run
  • reduce运行时间为4.0392ms
  • Math.max.apply took 3.3742ms to run
  • Math.max。应用花了3.3742毫秒运行
  • sorting and getting the 0th value took 67.4724ms to run
  • 排序和获取第0个值需要67.4724ms
  • Math.max within reduce() took 6.5804ms to run
  • 数学。在reduce()中max使用6.5804ms运行。
  • custom findmax function took 1.6102ms to run
  • 自定义findmax函数运行时间为1.6102ms

var performance = window.performance

function findmax(array)
{
  var max = 0,
      a = array.length,
      counter

  for (counter=0;counter<a;counter++)
  {
      if (array[counter] > max)
      {
          max = array[counter]
      }
  }
  return max
}

function findBiggestNumber(num) {
  var counts = []
  var i
  for (i = 0; i < num; i++) {
    counts.push(Math.random())
  }

  var a, b

  a = performance.now()
  var biggest = counts.reduce(function(highest, count){
        return highest > count ? highest : count
      }, 0)
  b = performance.now()
  console.log('reduce took ' + (b - a) + ' ms to run')

  a = performance.now()
  var biggest2 = Math.max.apply(Math, counts)
  b = performance.now()
  console.log('Math.max.apply took ' + (b - a) + ' ms to run')

  a = performance.now()
  var biggest3 = counts.sort(function(a,b){return b-a;})[0]
  b = performance.now()
  console.log('sorting and getting the 0th value took ' + (b - a) + ' ms to run')

  a = performance.now()
  var biggest4 = counts.reduce(function(highest, count){
        return Math.max(highest,count)
      }, 0)
  b = performance.now()
  console.log('Math.max within reduce() took ' + (b - a) + ' ms to run')

  a = performance.now()
  var biggest5 = findmax(counts)
  b = performance.now()
  console.log('custom findmax function took ' + (b - a) + ' ms to run')
  console.log(biggest + '-' + biggest2 + '-' + biggest3 + '-' + biggest4 + '-' + biggest5)

}

findBiggestNumber(1E5)

#6


27  

You could sort the array in descending order and get the first item:

您可以按降序对数组进行排序,得到第一项:

[267, 306, 108].sort(function(a,b){return b-a;})[0]

#7


18  

How about this:

这个怎么样:

var arr = [1,2,3,4];

var largest = arr.reduce(function(x,y){
       return (x > y) ? x : y;
});

console.log(largest);

#8


7  

how about using Array.reduce ?

如何使用数组。减少?

[0,1,2,3,4].reduce(function(previousValue, currentValue){
  return Math.max(previousValue,currentValue);
});

#9


5  

Finding max and min value the easy and manual way. This code is much faster than Math.max.apply; I have tried up to 1000k numbers in array.

求最大值和最小值的方法简单而手工。此代码比Math.max.apply快得多。我在数组中尝试了多达1000k的数字。

function findmax(array)
{
    var max = 0;
    var a = array.length;
    for (counter=0;counter<a;counter++)
    {
        if (array[counter] > max)
        {
            max = array[counter];
        }
    }
    return max;
}

function findmin(array)
{
    var min = array[0];
    var a = array.length;
    for (counter=0;counter<a;counter++)
    {
        if (array[counter] < min)
        {
            min = array[counter];
        }
    }
    return min;
}

#10


4  

Almost all of the answers use Math.max.apply() which is nice and dandy but has limitations.

几乎所有的答案都使用Math.max.apply(),这个方法很好,很好,但是有局限性。

Function arguments are placed onto stack which has a downside - a limit. So if your array is bigger than limit it will fail with RangeError: Maximum call stack size exceeded.

函数参数被放在堆栈上,堆栈有一个缺点——一个限制。因此,如果你的数组大于限制,它将会失败,并且超过了最大调用堆栈大小。

To find a call stack size I used this code:

为了找到调用堆栈大小,我使用了以下代码:

var ar = [];
for (var i = 1; i < 100*99999; i++) {
  ar.push(1);
  try {
    var max = Math.max.apply(Math, ar);
  } catch(e) {
    console.log('Limit reached: '+i+' error is: '+e);
    break;
  }
}

It proved to be biggest on FireFox on my machine - 591519. This means that if you array contains more than 591519 items, Math.max.apply() will result in RangeError.

它在我的机器上的火狐上被证明是最大的——591519。这意味着如果数组包含超过591519个项,Math.max.apply()将导致RangeError。

Best solution for this problem is iterative way(credit: https://developer.mozilla.org/):

解决这个问题的最佳方法是迭代方法(credit: https://developer.mozilla.org/):

max = -Infinity, min = +Infinity;

for (var i = 0; i < numbers.length; i++) {
  if (numbers[i] > max)
    max = numbers[i];
  if (numbers[i] < min)
    min = numbers[i];
}

I have written about this question on my blog here.

我已经在我的博客上写了这个问题。

#11


3  

Yes of course exist: Math.max.apply(null,[23,45,67,-45]) and the result return 67;

当然存在:Math.max.apply(null,[23,45,67,-45]),结果返回67;

#12


3  

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max

const inputArray = [ 1, 3, 4, 9, 16, 2, 20, 18];
const maxNumber = Math.max(...inputArray);
console.log(maxNumber);

#13


1  

Don't forget that the wrap can be done with Function.prototype.bind, giving you an "all-native" function.

不要忘记包装可以用Function.prototype完成。绑定,给你一个“全本机”功能。

var aMax = Math.max.apply.bind(Math.max, Math);
aMax([1, 2, 3, 4, 5]); // 5

#14


1  

You could also extend Array to have this function and make it part of every array.

你也可以扩展数组来得到这个函数并使它成为每个数组的一部分。

Array.prototype.max = function(){return Math.max.apply( Math, this )};
myArray = [1,2,3];

console.log( myArray.max() );

#15


1  

Find the largest number in a multidimensional array

var max = []; 

for(var i=0; arr.length>i; i++ ){

   var arra = arr[i];
   var largest = Math.max.apply(Math, arra);
   max.push(largest);

   }
return max;

#16


1  

You can also use forEach:

你也可以使用forEach:

var maximum = Number.MIN_SAFE_INTEGER;

var array = [-3, -2, 217, 9, -8, 46];
array.forEach(function(value){
  if(value > maximum) {
    maximum = value;
  }
});

console.log(maximum); // 217

#17


1  

Using - Array.prototype.reduce() is cool!

使用- Array.prototype.reduce()很酷!

[267, 306, 108].reduce((acc,val)=> (acc>val)?acc:val)

(267、306、108).reduce(acc,val)= >(acc > val)? acc:val)

where acc = accumulator and val = current value;

acc =累加器和val =当前值;

var a = [267, 306, 108].reduce((acc,val)=> (acc>val)?acc:val);

console.log(a);

#18


1  

You can try this,

你可以试试这个,

var arr = [267,306,108];
var largestNum = 0;
for(i=0;i<arr.length;i++) {
   if(arr[i]>largest){
    var largest = arr[i];
   }
}
console.log(largest);

#19


1  

I just started with JS but I think this method would be good:

我刚开始用JS,但我认为这个方法会很好:

var array = [34, 23, 57, 983, 198];<br>
var score = 0;

for(var i = 0; i = array.length; i++) {
  if(array[ i ] > score) {
    score = array[i];
  }
}

#20


0  

Run this:

运行这个:

Array.prototype.max = function(){
    return Math.max.apply( Math, this );
};

And now try [3,10,2].max() returns 10

现在尝试[3,10,2].max()返回10

#1


289  

Resig to the rescue:

Resig救援:

Array.max = function( array ){
    return Math.max.apply( Math, array );
};

#2


182  

You can use the apply function, to call Math.max:

可以使用apply函数调用Math.max:

var array = [267, 306, 108];
var largest = Math.max.apply(Math, array); // 306

How it works?

它是如何工作的?

The apply function is used to call another function, with a given context and arguments, provided as an array. The min and max functions can take an arbitrary number of input arguments: Math.max(val1, val2, ..., valN)

apply函数用于调用另一个函数,它具有给定的上下文和参数,作为数组提供。最小和最大函数可以取任意数量的输入参数:Math。max(val1,val2,…valN)

So if we call:

所以如果我们叫:

Math.min.apply(Math, [1,2,3,4]);

The apply function will execute:

应用函数将执行:

Math.min(1,2,3,4);

Note that the first parameter, the context, is not important for these functions since they are static, they will work regardless of what is passed as the context.

注意,第一个参数上下文对这些函数来说并不重要,因为它们是静态的,不管作为上下文传递的是什么,它们都可以工作。

#3


34  

I've found that for bigger arrays (~100k elements), it actually pays to simply iterate the array with a humble for loop, performing ~30% better than Math.max.apply():

我发现,对于更大的数组(~100k元素),使用简单的for循环迭代数组实际上是有好处的,其性能比Math.max.apply()好30%:

function mymax(a)
{
    var m = -Infinity, i = 0, n = a.length;

    for (; i != n; ++i) {
        if (a[i] > m) {
            m = a[i];
        }
    }

    return m;
}

Benchmark results

基准测试结果

#4


34  

The easiest syntax, with the new spread operator:

最简单的语法,使用新的扩展操作符:

var arr = [1, 2, 3];
var max = Math.max(...arr);

Source : Mozilla MDN

来源:Mozilla MDN

#5


32  

I'm no JS expert, but I wanted to see how these methods stack up, so this was good practice for me. I don't know if this is technically the right way to performance test these, but I just ran them one right after another, as you can see in my code.

我不是JS专家,但我想看看这些方法是如何组合在一起的,所以这对我来说是很好的实践。我不知道从技术上来说,这是否是进行性能测试的正确方法,但我只是一个接一个地运行它们,正如您在我的代码中看到的那样。

Sorting and getting the 0th value is by far the worst method (and it modifies the order of your array, which may not be desirable). For the others, the difference is negligible unless you're talking millions of indices.

排序和获取第0个值是迄今为止最糟糕的方法(并且它修改了数组的顺序,这可能不可取)。对于其他的,差别是可以忽略的,除非你说的是数以百万计的指数。

Average results of five runs with a 100,000-index array of random numbers:

拥有10万索引随机数的5次运行的平均结果:

  • reduce took 4.0392ms to run
  • reduce运行时间为4.0392ms
  • Math.max.apply took 3.3742ms to run
  • Math.max。应用花了3.3742毫秒运行
  • sorting and getting the 0th value took 67.4724ms to run
  • 排序和获取第0个值需要67.4724ms
  • Math.max within reduce() took 6.5804ms to run
  • 数学。在reduce()中max使用6.5804ms运行。
  • custom findmax function took 1.6102ms to run
  • 自定义findmax函数运行时间为1.6102ms

var performance = window.performance

function findmax(array)
{
  var max = 0,
      a = array.length,
      counter

  for (counter=0;counter<a;counter++)
  {
      if (array[counter] > max)
      {
          max = array[counter]
      }
  }
  return max
}

function findBiggestNumber(num) {
  var counts = []
  var i
  for (i = 0; i < num; i++) {
    counts.push(Math.random())
  }

  var a, b

  a = performance.now()
  var biggest = counts.reduce(function(highest, count){
        return highest > count ? highest : count
      }, 0)
  b = performance.now()
  console.log('reduce took ' + (b - a) + ' ms to run')

  a = performance.now()
  var biggest2 = Math.max.apply(Math, counts)
  b = performance.now()
  console.log('Math.max.apply took ' + (b - a) + ' ms to run')

  a = performance.now()
  var biggest3 = counts.sort(function(a,b){return b-a;})[0]
  b = performance.now()
  console.log('sorting and getting the 0th value took ' + (b - a) + ' ms to run')

  a = performance.now()
  var biggest4 = counts.reduce(function(highest, count){
        return Math.max(highest,count)
      }, 0)
  b = performance.now()
  console.log('Math.max within reduce() took ' + (b - a) + ' ms to run')

  a = performance.now()
  var biggest5 = findmax(counts)
  b = performance.now()
  console.log('custom findmax function took ' + (b - a) + ' ms to run')
  console.log(biggest + '-' + biggest2 + '-' + biggest3 + '-' + biggest4 + '-' + biggest5)

}

findBiggestNumber(1E5)

#6


27  

You could sort the array in descending order and get the first item:

您可以按降序对数组进行排序,得到第一项:

[267, 306, 108].sort(function(a,b){return b-a;})[0]

#7


18  

How about this:

这个怎么样:

var arr = [1,2,3,4];

var largest = arr.reduce(function(x,y){
       return (x > y) ? x : y;
});

console.log(largest);

#8


7  

how about using Array.reduce ?

如何使用数组。减少?

[0,1,2,3,4].reduce(function(previousValue, currentValue){
  return Math.max(previousValue,currentValue);
});

#9


5  

Finding max and min value the easy and manual way. This code is much faster than Math.max.apply; I have tried up to 1000k numbers in array.

求最大值和最小值的方法简单而手工。此代码比Math.max.apply快得多。我在数组中尝试了多达1000k的数字。

function findmax(array)
{
    var max = 0;
    var a = array.length;
    for (counter=0;counter<a;counter++)
    {
        if (array[counter] > max)
        {
            max = array[counter];
        }
    }
    return max;
}

function findmin(array)
{
    var min = array[0];
    var a = array.length;
    for (counter=0;counter<a;counter++)
    {
        if (array[counter] < min)
        {
            min = array[counter];
        }
    }
    return min;
}

#10


4  

Almost all of the answers use Math.max.apply() which is nice and dandy but has limitations.

几乎所有的答案都使用Math.max.apply(),这个方法很好,很好,但是有局限性。

Function arguments are placed onto stack which has a downside - a limit. So if your array is bigger than limit it will fail with RangeError: Maximum call stack size exceeded.

函数参数被放在堆栈上,堆栈有一个缺点——一个限制。因此,如果你的数组大于限制,它将会失败,并且超过了最大调用堆栈大小。

To find a call stack size I used this code:

为了找到调用堆栈大小,我使用了以下代码:

var ar = [];
for (var i = 1; i < 100*99999; i++) {
  ar.push(1);
  try {
    var max = Math.max.apply(Math, ar);
  } catch(e) {
    console.log('Limit reached: '+i+' error is: '+e);
    break;
  }
}

It proved to be biggest on FireFox on my machine - 591519. This means that if you array contains more than 591519 items, Math.max.apply() will result in RangeError.

它在我的机器上的火狐上被证明是最大的——591519。这意味着如果数组包含超过591519个项,Math.max.apply()将导致RangeError。

Best solution for this problem is iterative way(credit: https://developer.mozilla.org/):

解决这个问题的最佳方法是迭代方法(credit: https://developer.mozilla.org/):

max = -Infinity, min = +Infinity;

for (var i = 0; i < numbers.length; i++) {
  if (numbers[i] > max)
    max = numbers[i];
  if (numbers[i] < min)
    min = numbers[i];
}

I have written about this question on my blog here.

我已经在我的博客上写了这个问题。

#11


3  

Yes of course exist: Math.max.apply(null,[23,45,67,-45]) and the result return 67;

当然存在:Math.max.apply(null,[23,45,67,-45]),结果返回67;

#12


3  

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max

const inputArray = [ 1, 3, 4, 9, 16, 2, 20, 18];
const maxNumber = Math.max(...inputArray);
console.log(maxNumber);

#13


1  

Don't forget that the wrap can be done with Function.prototype.bind, giving you an "all-native" function.

不要忘记包装可以用Function.prototype完成。绑定,给你一个“全本机”功能。

var aMax = Math.max.apply.bind(Math.max, Math);
aMax([1, 2, 3, 4, 5]); // 5

#14


1  

You could also extend Array to have this function and make it part of every array.

你也可以扩展数组来得到这个函数并使它成为每个数组的一部分。

Array.prototype.max = function(){return Math.max.apply( Math, this )};
myArray = [1,2,3];

console.log( myArray.max() );

#15


1  

Find the largest number in a multidimensional array

var max = []; 

for(var i=0; arr.length>i; i++ ){

   var arra = arr[i];
   var largest = Math.max.apply(Math, arra);
   max.push(largest);

   }
return max;

#16


1  

You can also use forEach:

你也可以使用forEach:

var maximum = Number.MIN_SAFE_INTEGER;

var array = [-3, -2, 217, 9, -8, 46];
array.forEach(function(value){
  if(value > maximum) {
    maximum = value;
  }
});

console.log(maximum); // 217

#17


1  

Using - Array.prototype.reduce() is cool!

使用- Array.prototype.reduce()很酷!

[267, 306, 108].reduce((acc,val)=> (acc>val)?acc:val)

(267、306、108).reduce(acc,val)= >(acc > val)? acc:val)

where acc = accumulator and val = current value;

acc =累加器和val =当前值;

var a = [267, 306, 108].reduce((acc,val)=> (acc>val)?acc:val);

console.log(a);

#18


1  

You can try this,

你可以试试这个,

var arr = [267,306,108];
var largestNum = 0;
for(i=0;i<arr.length;i++) {
   if(arr[i]>largest){
    var largest = arr[i];
   }
}
console.log(largest);

#19


1  

I just started with JS but I think this method would be good:

我刚开始用JS,但我认为这个方法会很好:

var array = [34, 23, 57, 983, 198];<br>
var score = 0;

for(var i = 0; i = array.length; i++) {
  if(array[ i ] > score) {
    score = array[i];
  }
}

#20


0  

Run this:

运行这个:

Array.prototype.max = function(){
    return Math.max.apply( Math, this );
};

And now try [3,10,2].max() returns 10

现在尝试[3,10,2].max()返回10