Javascript массив максимальный элемент

Как найти самое большое число в массиве js

После сортировки методом sort() мы берем первый элемент результирующего массива, используя индекс [0] , и присваиваем его переменной max .

Для того, чтобы найти максимальный элемент в массиве, можно воспользоваться не только агрегацией. Давайте обратимся к стандартным возможностям языка и рассмотрим метод Math.max.apply():

const numbers = [-94, 87, 12, 0, -67, 32]; const maxValue = Math.max.apply(null, numbers); //обратите внимание, что в записи данного метода обязателен null. //Если забыть в записи данного выражения null, то в переменную maxValue вернётся -Infinity. console.log(maxValue); // => 87 

Есть ещё более хитрый способ использовать метод Math.max():
Для этого вспомним про spread оператор.

const numbers = [-94, 87, 12, 0, -67, 32]; const maxValue = Math.max(. numbers); console.log(maxValue); // => 87 

И невозможно не упомянуть про библиотеку Lodash с методом _.max():

const numbers = [-94, 87, 12, 0, -67, 32]; const maxValue = _.max(numbers); console.log(maxValue); // => 87 

Источник

Math.max()

Метод Math.max() возвращает наибольшее из нуля или более чисел.

Синтаксис

Параметры

Описание

Поскольку метод max() является статическим методом объекта Math , вы всегда должны использовать его как Math.max() , а не пытаться вызывать метод на созданном экземпляре объекта Math (поскольку объект Math не является конструктором).

При вызове без аргументов результатом вызова будет значение — Infinity .

Если хотя бы один из аргументов не может быть преобразован в число, результатом будет NaN .

Примеры

Пример: использование метода Math.max()

.max(10, 20); // 20 Math.max(-10, -20); // -10 Math.max(-10, 20); // 20 

Нахождение максимального элемента в массиве

Следующая функция использует метод Function.prototype.apply() для нахождения максимального элемента в числовом массиве. Вызов getMaxOfArray([1, 2, 3]) эквивалентен вызову Math.max(1, 2, 3) , однако вы можете использовать функцию getMaxOfArray() вместе с программно сконструированными массивами любого размера. Рекомендуется использовать только в случае обработки массивов с небольшим количеством элементов.

function getMaxOfArray(numArray)  return Math.max.apply(null, numArray); > 

Спецификации

Совместимость с браузерами

BCD tables only load in the browser

Смотрите также

Found a content problem with this page?

This page was last modified on 7 нояб. 2022 г. by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

Найти максимальное / минимальное значение в массиве JavaScript

Найти максимальное / минимальное значение в массиве JavaScript

  1. Найдите минимальное значение массива с помощью функции Math.min() в JavaScript
  2. Найдите максимальное значение массива с помощью функции Math.max() в JavaScript

В этом руководстве будет обсуждаться, как найти минимальное и максимальное значение массива с помощью функций Math.min() и Math.max() в JavaScript.

Найдите минимальное значение массива с помощью функции Math.min() в JavaScript

Чтобы найти минимальное значение, присутствующее в данном массиве, мы можем использовать функцию Math.min() в JavaScript. Эта функция возвращает минимальное значение, присутствующее в данном массиве. Например, давайте определим массив с некоторыми случайными значениями и найдем его минимальное значение с помощью функции Math.min() и выведем его на консоль с помощью функции console.log() . См. Код ниже.

var myArray = [1, 5, 6, 2, 3]; var m = Math.min(. myArray); console.log(m) 

Как видно из вывода, минимальное значение массива возвращается функцией Math.min() . Некоторые браузеры могут не поддерживать вышеуказанный метод, поэтому вы можете использовать функцию apply() вместе с функцией Math.min() , чтобы получить минимальное значение из заданного массива. Например, см. Приведенный ниже код.

var myArray = [1, 5, 6, 2, 3]; var m = Math.min.apply(null, myArray); console.log(m) 

Функция apply() вызывает функцию с заданным значением this и заданным массивом в приведенном выше коде. Если вы не хотите использовать какую-либо предопределенную функцию, вы можете создать свою собственную функцию, используя цикл в JavaScript. Например, давайте создадим функцию для поиска минимального значения массива. См. Код ниже.

function MyMin(myarr)  var al = myarr.length;  minimum = myarr[al-1];  while (al--)  if(myarr[al]  minimum)  minimum = myarr[al]  >  >  return minimum; >; var myArray = [1, 5, 6, 2, 3]; var m = MyMin(myArray); console.log(m) 

В приведенном выше коде мы сохранили последний элемент данного массива в переменной minimum и сравнили его с предыдущим элементом. Если элемент меньше переменной minimum , мы сохраним этот элемент в переменной minimum . А если нет, то перейдем к следующему элементу. Мы будем повторять эту процедуру до тех пор, пока не дойдем до индекса 0. После цикла мы вернем переменную minimum .

Найдите максимальное значение массива с помощью функции Math.max() в JavaScript

Чтобы найти максимальное значение, присутствующее в данном массиве, мы можем использовать функцию Math.max() в JavaScript. Эта функция возвращает максимальное значение, присутствующее в данном массиве. См. Код ниже.

var myArray = [1, 5, 6, 2, 3]; var m = Math.max(. myArray); console.log(m) 

Вы также можете использовать функцию apply() вместе с функцией Math.max() , чтобы получить максимальное значение из заданного массива. Например, см. Приведенный ниже код.

var myArray = [1, 5, 6, 2, 3]; var m = Math.max.apply(null, myArray); console.log(m) 

Создадим функцию, чтобы найти максимальное значение массива. См. Код ниже.

function MyMax(myarr)  var al = myarr.length;  maximum = myarr[al-1];  while (al--)  if(myarr[al] > maximum)  maximum = myarr[al]  >  >  return maximum; >; var myArray = [1, 5, 6, 2, 3]; var m = MyMax(myArray); console.log(m) 

Hello! I am Ammar Ali, a programmer here to learn from experience, people, and docs, and create interesting and useful programming content. I mostly create content about Python, Matlab, and Microcontrollers like Arduino and PIC.

Сопутствующая статья — JavaScript Array

Copyright © 2023. All right reserved

Источник

JavaScript: Get Min and Max Element of Array

When working with JavaScript, we oftentimes encounter situations that require us to obtain the minimum and maximum elements of an array — be it for setting boundaries for a slider or displaying the statistics to a user.

In this article, we’ll take a look at how to get the minimum and the maximum element of an array in JavaScript. We’ll also look at four different methods and compare their speeds when dealing with large arrays.

How to Get Min and Max Elements of an Array Using the Math Object

Math is JavaScript’s built-in global convenience object containing a lot of methods and constants you might need when performing mathematical operations. Two methods that we’ll use in this article are Math.min() and Math.max() — both of them accept a list of numbers as arguments. As their names suggest, one returns the element with the lowest value, and the other returns one whose value is the highest:

console.log(Math.min(20, 23, 27)); // 20 console.log(Math.max(20, 23, 27)); // 27 console.log(Math.min(-20, -23, -27)); // -27 console.log(Math.max(-20, -23, -27)); // -20 

If at least one of the passed elements is not a number or cannot be converted to a number, both Math.min() and Math.max() returns NaN :

console.log(Math.min('-20', -23, -27)); // -27 console.log(Math.max('number', -23, -27)); // NaN 

Similarly, if we try to pass an array as an argument of the Math.min() function, we get a NaN , since it’s treated as a single element, which can’t be converted to a scalar value:

const myArray = [2, 3, 1]; console.log(Math.min(myArray)); // NaN 

However, a quick fix for this is to use the spread operator to unwrap the elements:

const myArray = [2, 3, 1]; console.log(Math.min(. myArray)); // 1 

If you’d like to read more about the Spread Operator — read our Guide to the Spread Operator in JavaScript!

Get Max and Min Element with reduce()

Reduction operations, sometimes known as folding, are some of the most powerful operations from functional programming, with a wide variety of applications. The reduce() function, runs a reducer function (defined in a callback) on each array element and returns a single value in the end.

It’s worth covering the method due to how universally it can be applied:

const myArray = [20, 23, 27]; let minElement = myArray.reduce((a, b) => < return Math.min(a, b); >); console.log(minElement); // 20 

Find Min and Max Element with apply()

The apply() method is used to invoke a function with a given this value and an array of arguments. This makes it possible for us to enter arrays into the Math.min() static function:

const myArray = [20, 23, 27]; let minElement = Math.min.apply(Math, myArray); console.log(minElement); // 20 // Or let minElement = Math.min.apply(null, myArray); console.log(minElement); // 20 

Getting Min and Max Elements With Standard Loops — Fastest Performance

Loops are used in JavaScript to perform repeated tasks based on a condition. Conditions return true or false . A loop will continue running until the defined condition returns false . In our case, we will be making use of the for loop — it is commonly used to run code a number of times.

Get Minimum Element

First, we’ll initialize the minimum element to the first element of an array. Then, we loop through the entire array to see if the value of any other element is less than the current minimum value — if it is, we’ll set the new minimum value to the value of the current element:

const myArray = [20, 23, 27]; let minElement = myArray[0]; for (let i = 1; i < arrayLength; ++i) < if (myArray[i] < minElement) < minElement = myArray[i]; >> console.log(minElement); // 20 

Get Maximum Element

We’ll first initialize the maximum element to the first element in the array. Then we will loop through the entire array to see if any other element is greater than the initialized element, so it replaces it:

const myArray = [20, 23, 27]; let maxElement = myArray[0]; for (let i = 1; i < arrayLength; ++i) < if (myArray[i] > maxElement) < maxElement = myArray[i]; >> console.log(maxElement); // 27 

Performance Benchmark

Using JS Benchmark — we’ve run all of these approaches on varying input, from 100 to 1000000 elements in the array. The performance is relative, and depends on the length of the array.

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

  • For small arrays (100), the reduce() method performed the best, followed by standard loops, the spread operator and then the apply() method. The runner ups are almost equal in performance.
  • For medium arrays (1000), the standard loops perform the best, followed by reduce() , the spread operator and the apply() method. Standard loops significantly faster than reduce() here, which in turn, is fairly faster than the runner ups.
  • For really large arrays (1000000), the standard loops outperform all other methods to such a large degree that the case for standard loops is very strong.

Standard loops scale really well, and only lose out to the competition when applied to small arrays. If you’re dealing with a few items, or smaller arrays, all of the methods will be fairly seamless. The larger the array, the bigger the benefit of using standard loops.

Note: Don’t take benchmarks at face value! They’re run on different machines, with likely different browser versions and JS engines. Test these out in your application and choose the scalable, fastest option for your own use case.

Conclusion

In this guide, we’ve taken a look at how to get the minimum and maximum elements of an array in JavaScript. We’ve taken a look at the Math.min() and Math.max() methods, the spread operator, the reduce() method, the apply() method and wrote a custom approach to getting the elements through a for loop.

Finally, we’ve benchmarked the results, noting that it doesn’t really matter which approach you use for small arrays, while you should tend to use standard for loops for larger arrays.

Источник

Читайте также:  Проверка склейки index html
Оцените статью