The easiest way to do this would be to sort the array, then return the first two and last two elements.

Using slice() prevents the array itself from being sorted:

var numbers = [2, 4, 9, 2, 0, 16, 24];

var sorted = numbers.slice().sort(function(a, b) {
  return a - b;
});

var smallest = sorted[0],                      
    secondSmallest = sorted[1],                
    secondLargest = sorted[sorted.length - 2], 
    largest  = sorted[sorted.length - 1];

console.log('Smallest: ' + smallest);
console.log('Second Smallest: ' + secondSmallest);
console.log('Second Largest: ' + secondLargest);
console.log('Largest: ' + largest);

Answer from Rick Hitchcock on Stack Overflow
๐ŸŒ
DEV Community
dev.to โ€บ melvin2016 โ€บ how-to-get-the-highest-and-lowest-number-from-an-array-in-javascript-21ml
How to get the highest and lowest number from an array in JavaScript? - DEV Community
November 29, 2020 - // number array const numberArr = [23, 122, 1, 23, 4, 56]; // get highest number const highest = Math.max(...numberArr); // get lowest number const lowest = Math.min(...numberArr); console.log("Highest Number: " + highest); // Highest Number: ...
๐ŸŒ
Quora
quora.com โ€บ How-can-you-find-the-highest-and-lowest-in-an-array-of-objects-JavaScript-Javascript-arrays-object-average-development
How to find the highest and lowest in an array of objects/JavaScript (Javascript, arrays, object, average, development) - Quora
Iterate through the array and check each element against the variables holding the highest and lowest numbers. If the current element is higher that the highest value, set highest value to current element.
Discussions

Find the smallest and largest value in an array with JavaScript - Stack Overflow
I am trying to write an algorithm that finds and smallest and largest value in an array, and the second largest and second smallest. I tried with the following: numbers = [2, 4, 9, 2, 0, 16,... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Finding largest integer in an array in JavaScript - Stack Overflow
Possible Duplicate: How might I find the largest number contained in a JavaScript array? I am having trouble getting this code to work. I have been at it for a while trying to figure it out. When ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
javascript - Finding lowest and highest number number value in an Array - Stack Overflow
I am struggling to workout how this code is working, how is the maxNum part working? maxNum[0] More on stackoverflow.com
๐ŸŒ stackoverflow.com
How can I find highest and lowest in an array of objects/ Javascript - Stack Overflow
Your inner loop is using weather.length ... to the number of months. Once you've got the correct average for each month, you would then need to find the minimum of those averages, and the maximum of those averages. How can you do that? ... I've mutated the object and added lowest, 'highest', and 'average' in the object itself. To get the month and temperature, I've used object destructuring. Then sort the array using sort ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
Melvin George
melvingeorge.me โ€บ blog โ€บ lowest-highest-number-array-javascript
How to get the highest and lowest number from an array in JavaScript? | MELVIN GEORGE
November 29, 2020 - To get the highest or lowest number from an array in JavaScript, you can use the Math.max() or the Math.min() methods then spread the elements from the array to these methods using the spread operator (...).
๐ŸŒ
MDN Web Docs
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Web โ€บ JavaScript โ€บ Reference โ€บ Global_Objects โ€บ Math โ€บ max
Math.max() - JavaScript - MDN Web Docs
... The Math.max() static method returns the largest of the numbers given as input parameters, or -Infinity if there are no parameters. console.log(Math.max(1, 3, 2)); // Expected output: 3 console.log(Math.max(-1, -3, -2)); // Expected output: -1 const array = [1, 3, 2]; console.log(Math....
๐ŸŒ
Medium
medium.com โ€บ coding-at-dawn โ€บ the-fastest-way-to-find-minimum-and-maximum-values-in-an-array-in-javascript-2511115f8621
The Fastest Way to Find Minimum and Maximum Values in an Array in JavaScript | by Dr. Derek Austin ๐Ÿฅณ | Coding at Dawn | Medium
January 4, 2023 - There are several built-in ways to find a minimum or maximum value from an array in JavaScript, including using the Math functions with the spread operator (โ€ฆ) and sorting the array numerically with .sort(). In this article, I explain how ...
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ highest-and-lowest-in-an-array-javascript
Highest and lowest in an array JavaScript
August 19, 2020 - const arr = [23,54,65,76,87,87,431,-6,22,4,-454]; const arrayDifference = (arr) => { let min, max; arr.forEach((num, index) => { if(index === 0){ min = num; max = num; }else{ min = Math.min(num, min); max = Math.max(num, max); }; }); return max - min; }; console.log(arrayDifference(arr));
Find elsewhere
๐ŸŒ
Bobby Hadz
bobbyhadz.com โ€บ blog โ€บ javascript-get-index-of-max-value-in-array
Get the Index of the Max/Min value in Array in JavaScript | bobbyhadz
We used the Mah.min() method to find the min value in the array and used a for loop to iterate over the array.
๐ŸŒ
W3Resource
w3resource.com โ€บ javascript-exercises โ€บ javascript-math-exercise-6.php
JavaScript Math: Find the highest value in an array - w3resource
// Define a function named max that takes an input array. function max(input) { // Check if the input is an array, if not, return false. if (toString.call(input) !== "[object Array]") return false; // Return the maximum value from the input array using Math.max.apply. return Math.max.apply(null, input); } // Output the maximum value from the array [12, 34, 56, 1] to the console. console.log(max([12, 34, 56, 1])); // Output the maximum value from the array [-12, -34, 0, -56, -1] to the console. console.log(max([-12, -34, 0, -56, -1])); ... See the Pen javascript-math-exercise-6 by w3resource (@w3resource) on CodePen. ... Write a JavaScript function that finds the maximum number in an array using recursion instead of Math.max.
Top answer
1 of 4
1

Both start at 2 in this example

let minNum = numbers[0]//equals first element in the numbers array and thats 2 in this example
let maxNum = numbers[0]// equals 2 as well

Then you start to iterate thru the numbers array

Lets cover how you get your lowest number first:

if(minNum > numbers[i]){

1st loop
minNum = 2 not greater than 2, nothing happens
2nd loop 
minNum = 2 not greater than 9, nothing happens
3rd loop
minNum = 2 not greater than 10, nothing happens
4th loop
minNum = 2 not greater than 17, nothing happens
last loop
minNum = 2 not greater than 45, nothing happens

minNum = never changes during the entire iteration becuz no number lesser than 2 was found so it keeps the initial value

Now for the maxNum:

 } else if (maxNum < numbers[i]){

1st loop
maxNum= 2, numbers[i]=2, numbers[i] not greater than maxNum, nothing happens
2nd loop 
maxNum= 2, numbers[i]=9, numbers[i] is greater than maxNum, maxNum=9 now
3rd loop
maxNum= 9, numbers[i]=10, numbers[i] is greater than maxNum, maxNum=10 now
4th loop
maxNum= 10, numbers[i]=17, numbers[i] is greater than maxNum, maxNum=17 now
last loop
maxNum= 17, numbers[i]=45, numbers[i] is greater than maxNum, maxNum=45 now

maxNum will overwrite itself as long as you can find a number that's higher than the value previously stored. Hopefully that explains what you don't understand

2 of 4
0

Given to a context I dont fully get I would estimate that you want to know how the comparison works.

function sortThem(numbers) {

  let minNum = numbers[0]
  let maxNum = numbers[0]

  for (let i = 0; i < numbers.length; i++) { // you can start loop at index 1 since you have set default val to 0
    if (minNum > numbers[i]) { // if my current number in array is smaller than the most recent minNum
      minNum = numbers[i] // set minNum to current number Exit out of if/else structure since else will not be triggered
    } else if (maxNum < numbers[i]) { // if currentNumber is greater than given maxNum
      maxNum = numbers[i] //set maxnum to current number
    }
  }

  console.log(maxNum)

  const minMax = [minNum, maxNum] //useless
  return minMax // return [minNum, maxNum];

}

const results = sortThem([2, 9, 10, 17, 45])

console.log(results)

No Idea if it answered your question, but I think thats the explanation of this function.

๐ŸŒ
W3Schools
w3schools.com โ€บ jsref โ€บ jsref_max.asp
JavaScript Math max() Method
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING INTRO TO HTML & CSS BASH RUST TOOLS ... Array[ ] Array( ) at() concat() constructor copyWithin() entries() every() fill() filter() find() findIndex() findLast() findLastIndex() flat() flatMap() forEach() from() includes() indexOf() isArray() join() keys() lastIndexOf() length map() of() pop() prototype push() reduce() reduceRight() rest (...) reverse() shift() slice() some() sort() splice() spread (...) toReversed() toSorted() toSpliced() toString() unshift() values() valueOf() with() JS Boolean
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ finding-the-largest-and-smallest-number-in-an-unsorted-array-of-integers-in-javascript
Finding the largest and smallest number in an unsorted array of integers in JavaScript
So first we will initialize two variables to store the smallest and largest numbers of the array. Then we will iterate the remaining items and compare every item with the current smallest and largest values. And if we found the values then we will update in the respective variables. At the end of the iteration process we will have the values of smallest and largest elements of the array without sorting the array. Step 1: As our task is to find the smallest and highest values from the given input array without sorting the array.
๐ŸŒ
DEV Community
dev.to โ€บ domhabersack โ€บ getting-the-largest-number-from-an-array-e97
๐Ÿ”ฅ Getting the largest number from an array - DEV Community
January 5, 2021 - Math.max() returns the largest of zero or more numbers passed to it. We can use the spread operator w... Tagged with javascript.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 66828470 โ€บ how-can-i-find-highest-and-lowest-in-an-array-of-objects-javascript
How can I find highest and lowest in an array of objects/ Javascript - Stack Overflow
Use map & reduce. Inside map callback use Math.max & Math.min to find highest and lowest temperature and use sort to sort the array by ascending order of average temperature
๐ŸŒ
Seanconnolly
seanconnolly.dev โ€บ javascript-find-element-with-max-value
How to get the element with the max value in a JavaScript array ยท Sean Connolly
So the next time you need a quick and easy way to find that array element with the most or least of something, I hope you will consider Array.reduce!
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ three-ways-to-return-largest-numbers-in-arrays-in-javascript-5d977baa80a1
Three ways you can find the largest number in an array using JavaScript
October 17, 2016 - In this article, Iโ€™m going to explain how to solve Free Code Campโ€™s โ€œReturn Largest Numbers in Arraysโ€ challenge. This involves returning an array with the largest numbers from each of the sub arrays. There are the three approaches Iโ€™ll cover: with ...
Top answer
1 of 16
251

The tersest expressive code to find the minimum value is probably rest parameters:

const arr = [14, 58, 20, 77, 66, 82, 42, 67, 42, 4]
const min = Math.min(...arr)
console.log(min)


Rest parameters are essentially a convenient shorthand for Function.prototype.apply when you don't need to change the function's context:

var arr = [14, 58, 20, 77, 66, 82, 42, 67, 42, 4]
var min = Math.min.apply(Math, arr)
console.log(min)


This is also a great use case for Array.prototype.reduce:

const arr = [14, 58, 20, 77, 66, 82, 42, 67, 42, 4]
const min = arr.reduce((a, b) => Math.min(a, b))
console.log(min)

It may be tempting to pass Math.min directly to reduce, however the callback receives additional parameters:

callback (accumulator, currentValue, currentIndex, array)

In this particular case it may be a bit verbose. reduce is particularly useful when you have a collection of complex data that you want to aggregate into a single value:

const arr = [{name: 'Location 1', distance: 14}, {name: 'Location 2', distance: 58}, {name: 'Location 3', distance: 20}, {name: 'Location 4', distance: 77}, {name: 'Location 5', distance: 66}, {name: 'Location 6', distance: 82}, {name: 'Location 7', distance: 42}, {name: 'Location 8', distance: 67}, {name: 'Location 9', distance: 42}, {name: 'Location 10', distance: 4}]
const closest = arr.reduce(
  (acc, loc) =>
    acc.distance < loc.distance
      ? acc
      : loc
)
console.log(closest)


And of course you can always use classic iteration:

var arr,
  i,
  l,
  min

arr = [14, 58, 20, 77, 66, 82, 42, 67, 42, 4]
min = Number.POSITIVE_INFINITY
for (i = 0, l = arr.length; i < l; i++) {
  min = Math.min(min, arr[i])
}
console.log(min)

...but even classic iteration can get a modern makeover:

const arr = [14, 58, 20, 77, 66, 82, 42, 67, 42, 4]
let min = Number.POSITIVE_INFINITY
for (const value of arr) {
  min = Math.min(min, value)
}
console.log(min)

2 of 16
130

Jon Resig illustrated in this article how this could be achieved by extending the Array prototype and invoking the underlying Math.min method which unfortunately doesn't take an array but a variable number of arguments:

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

and then:

var minimum = Array.min(array);
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ highest-and-lowest-value-difference-of-array-javascript
Highest and lowest value difference of array JavaScript
August 14, 2023 - So the number of iterations is proportional to the number of elements in the array so the resulting complexity is linear. We can solve the given problem by iterating the array elements with a for loop. And finding the highest and lowest values from the array and calculating the difference between ...