Languages
[Edit]
EN

JavaScript - max value in array

3 points
Created by:
Niac
208

In this article, we would like to show you how to find maximum value in array in JavaScript.

Quick solution:

let numbers = [2, 3, 1]

let max = Math.max(...numbers)

console.log(max);  // 3

 

1. Math.max()

In this example, we use Math.max() method with the spread operator (...) to find maximum value of the numbers array. 

// ONLINE-RUNNER:browser;

let numbers = [2, 3, 1]

let max = Math.max(...numbers)

console.log(max);  // 3

2. Add function to Array.prototype

In this example, we add a new function .max() to the Array() object so we can use it on every array as it was a built-in function.

// ONLINE-RUNNER:browser;

let numbers = [2, 3, 1]

Array.prototype.max = function() {
  return Math.max.apply(null, this);
};

console.log(numbers.max());  // 3

Related posts

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join