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 OverflowFind the smallest and largest value in an array with JavaScript - Stack Overflow
Finding largest integer in an array in JavaScript - Stack Overflow
javascript - Finding lowest and highest number number value in an Array - Stack Overflow
How can I find highest and lowest in an array of objects/ Javascript - Stack Overflow
Videos
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);
Move your console.log statements outside of your for loop.
var arr = [3, 6, 2, 56, 32, 5, 89, 32];
var largest = arr[0];
for (var i = 0; i < arr.length; i++) {
if (arr[i] > largest ) {
largest = arr[i];
}
}
console.log(largest);
- You need to define
ior else it become a global variable. - Don't redefine largest in the loop.
- Since you're looping through the array, use
i < array.lengthinstead ofi <= largest. - Since you're comparing each of the items in the array to
largest, useif(largest < array[i])instead ofif(array > largest) - You should set largest equal to the first element in the array because what if all the numbers are negative?
arrayis a bad variable name because it's too similar toArray(the array constructor). Tryarrinstead.
One liner:
var largest = Math.max.apply(0, array);
More info here: Javascript max() function for 3 numbers
var array = [3, 6, 2, 56, 32, 5, 89, 32];
var largest = 0;
for (let i=0; i < array.length; i++) {
if (array[i] > largest) {
largest = array[i];
}
}
console.log(largest);
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
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.
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)
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);