find largest item in array in javascript

To find the largest item in an array in JavaScript, one way is to loop through the array and compare each element with a variable that holds the current maximum value. Here's an example:

index.tsx
// Example array
const arr = [11, 2, 43, 17, 25, 16];

// Set the initial maximum value as the first element in the array
let max = arr[0];

// Loop through the rest of the array and compare each element with the current maximum
for (let i = 1; i < arr.length; i++) {
  if (arr[i] > max) {
    max = arr[i];
  }
}

console.log(max); // Output: 43
347 chars
15 lines

Another way is to use the Math.max() method with the spread syntax (...) to pass all the elements of the array as separate arguments:

index.tsx
// Example array
const arr = [11, 2, 43, 17, 25, 16];

// Use Math.max() with spread syntax to find the maximum value in the array
const max = Math.max(...arr);

console.log(max); // Output: 43
194 chars
8 lines

Note that this method can throw a RangeError if the array has too many elements.

gistlibby LogSnag