JS-152-Objects-Arrays
  • Introduction
  • 04-Objects
    • OOP-Basics
      • Overview
      • Coding the Example
    • Prototypes
      • Object Prototypes
      • Prototypes Continued
    • Inheritance
      • Inheritance
    • Synopsis
      • Synopsis
    • Challenges
    • Solutions
      • Constructor Function
        • Person Constructor
        • Explanation
      • Inheritance Challenge
        • Code
        • Explanation
      • Family Challenge
        • Child
        • Pet
  • 05-Arrays
    • Array Basics
      • Array Overview
      • Creating an Array
      • Individual Elements and Length
      • Iterating Over Arrays
    • Array Methods
      • Methods Overview
      • .join() Method
      • .reverse() Method
      • .split() Method
      • .replace() Method
      • .splice() Method
      • .map() Method
      • .indexOf() Method
      • .filter() Method
      • .every() Method
    • Palindrome Algorithm
    • Array Challenges
    • Solutions
      • First and Last
        • First Element
        • Last Element
      • Most Frequent
      • Largest and Smallest
        • Single Array
        • Multiple Arrays
      • Missing Number
      • "Arrays" in the DOM
      • Sorting
        • Bubble Sort
        • Selection Sort
    • Resources
Powered by GitBook
On this page
  • Completed Code
  • Explanation
  • Smallest
  1. 05-Arrays
  2. Solutions
  3. Largest and Smallest

Single Array

Completed Code

var arr= [ 68, 47, 85, 22];
console.log(Math.max.apply(null, arr));

Explanation

We use a new function here: Math.max.apply(null, arr). Let's break each part down:

  • Math - an object that allows us to do math stuff like rounding, getting the square root, trigonometry, and exponentiation.

  • .max - returns the maximum, the number with the highest value.

  • .apply - JavaScript arrays don't have a max() method so you have to apply it. Otherwise it would output NaN or Not a Number.

  • (null, arr) - the first argument of apply() sets the value of this. We don't have a this in our function so just set it to null. arr is just our array variable.

Smallest

If you want to calculate the smallest number in an array, just replace .max() with .min() to return the minimum.

var arr= [ 68, 47, 85, 22];
console.log(Math.min.apply(null, arr));
PreviousLargest and SmallestNextMultiple Arrays

Last updated 7 years ago