- Как найти самое большое число в массиве js
- Найти максимальное / минимальное значение в массиве JavaScript
- Найдите минимальное значение массива с помощью функции Math.min() в JavaScript
- Найдите максимальное значение массива с помощью функции Math.max() в JavaScript
- Сопутствующая статья — JavaScript Array
- Math.max()
- Синтаксис
- Параметры
- Описание
- Примеры
- Пример: использование метода Math.max()
- Нахождение максимального элемента в массиве
- Спецификации
- Совместимость с браузерами
- Смотрите также
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- How to Find the Min/Max Elements in an Array in JavaScript
- Math.max()
- Example:
- apply()
- Example:
- The spread operator
- The standard loop
- Example:
- reduce()
- Example:
- Maximum Size of the Array
Как найти самое большое число в массиве 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
Найти максимальное / минимальное значение в массиве JavaScript
- Найдите минимальное значение массива с помощью функции Math.min() в JavaScript
- Найдите максимальное значение массива с помощью функции 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
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.
How to Find the Min/Max Elements in an Array in JavaScript
There are multiple methods to find the smallest and largest numbers in a JavaScript array, and the performance of these methods varies based on the number of elements in the array. Let’s discuss each of them separately and give the testing results in the end.
Math.max()
For regular arrays you can use the Math.max with three dots:
let max = Math.max(. arrayOfNumbers);
Example:
Javascript Math.max find max in array
Using the three dots (…) makes it easy to call any function expecting arguments.
apply()
The Math.max function uses the apply() method to find the maximum element in a numeric array:
Math.min.apply(Math, testArr); Math.max.apply(Math, testArr);
Example:
Javascript Math.max.apply find max element in array
let arrayOfNumbers = [4, 12, 62, 70, -10]; console.log(Math.max.apply(Math, arrayOfNumbers)); // returns 70
The spread operator
The spread operator is also used to get the maximum of an array. It expands an array of numbers into the list of arguments, such as with Math.min() and Math.max() :
Math.min(. testArr); Math.max(. testArr); Math.min.apply(Math, testArr); Math.max.apply(Math, testArr);
The standard loop
You can use the standard loop for tons of arguments as for loop doesn’t have size limitation:
let max = testArray[0]; for (let i = 1; i < testArrayLength; ++i) < if (testArray[i] > max) < max = testArray[i]; > > let min = testArray[0]; for (let i = 1; i < testArrayLength; ++i) < if (testArray[i] < min) < min = testArray[i]; > >
Example:
Javascript the standard loop find max element in array
let arrayList = [1, 2, 3, 4, 3, 21, 0]; let max = arrayList[0]; for (let i = 1; i < arrayList.length; ++i) < if (arrayList[i] >max) < max = arrayList[i]; >> console.log(max);
reduce()
You can also use the reduce() method for getting the number of items:
testArr.reduce(function (a, b) < return Math.max(a, b); >); testArr.reduce(function (a, b) < return Math.min(a, b); >);
Example:
Javascript reduce() method for get the max ar min number of items
let arrayList = [1, 2, 3, 4, 3, 20, 0]; let maxNum = arrayList.reduce((prev, current) => < return Math.max(prev, current) >); console.log(maxNum);
Maximum Size of the Array
The apply and spread methods had a limitation of 65536 which came from the limit of the maximum number of arguments. In 2019, the limit is the maximum size of the call stack, meaning that the maximum size for the numbers in case of apply and spread solutions is approximately 120000. The following script will calculate the limit for your particular environment:
let testArr = Array.from(< length: 10000 >, () => Math.floor(Math.random() * 2000000)); for (i = 10000; i < 1000000; ++i) < testArr.push(Math.floor(Math.random() * 2000000)); try < Math.max.apply(null, testArr); > catch (e) < console.log(i); break; > >
When you test all the given examples above, the results show that the standard loop is the fastest. Then come the apply and spread methods, after them comes the reduce, which is the slowest one. When dealing with large arrays of more than 40 elements, the spread operator is considered a worse choice compared to other methods.