Get The Min/Max Elements of An Array in Javascript

Get The Min/Max Elements of An Array in Javascript

Hi guys! Today, you’ll learn how to get the min/max elements of an array in Javascript. Some of the methods that will be covered in this article are: Using Array.sort() or a combination of Math.min()/Math.max() and a Spread Syntax (...). Let’s check it out!

Get the min/max elements of an array in Javascript

Using Array.sort()

The Array.sort() function sorts an array by converting each value into a UTF-8 string and comparing the values based on that (Defaults to ascending).

By that logic, you cannot sort an Number array unless you use the callback. To sort with callback, it must return 0 (No sorting happens), > 0 (Sort a after b) or < 0 (Sort a before b).

By using the Array.sort() function, to get the min and max value of the array, you simply take the first and last value of the array.

Syntax:

Array.sort(function(a, b)? callback)

Parameters:

NameTypeDescription
callbackfunction/noneIf none: Converts all the values to UTF-8 String and sorting by it’s code units values
If function: Will sort depending on the return value (=== 0 / > 0 / < 0)
aThe first value to compare
bThe second value to compare

Callback function return values:

> 0Sort a after b
< 0Sort a before b
=== 0No sort

Example:

const arr1 = ["www", "LearnShareIT", ".com"];
arr1.sort();

const arr2 = [21, 1, 2006];

arr2.sort((a, b) => {
	if (a > b) return 1;
	if (a < b) return -1;
	if (a === b) return 0;
});

console.log(`arr1 Min: ${arr1[0]}`);
console.log(`arr1 Max: ${arr1[arr1.length - 1]}`);
console.log(`arr2 Min: ${arr2[0]}`);
console.log(`arr2 Max: ${arr2[arr2.length - 1]}`);

Output:

arr1 Min: .com
arr1 Max: www
arr2 Min: 1
arr2 Max: 2006

Using Math.max(), Math.min() and Spread Syntax

The Math.max() and Math.min() function simply returns the max/min value of a list of numbers.

To get that list of numbers (vals) from the array you need the Spread Syntax (...), which deconstructs an array into arguments.

Though please keep in mind that Math.max() and Math.min() only applies to Numbers and not Strings. While converting a String into UTF-8 codes and comparing each value is technically possible, it would be extremely long and difficult. So just stick with Array.sort() to sorting Strings.

Syntax:

Math.min(...vals)
Math.max(...vals)

Parameters:

…valsArguments (int)A list of arguments (1-n arguments)

Example:

const arr = [21, 1, 2006];
console.log(`arr Max: ${Math.max(...arr)}`);
console.log(`arr Min: ${Math.min(...arr)}`);

Output:

arr Max: 2006
arr Min: 1

Summary

To get the min/max elements of an array in JavaScript, you can use one of the methods described in this article. Hope it will be useful to you. Thanks for reading!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *