Find the min/max element of an Array containing strings in JavaScript

Tags:



How can I obtain the max number of a JavaScript Array containing strings?

const array = ['a', 3, 4, 2] // should return 4

Here’s my answer but I got NaN

function maxNum(arr) {
 for(let i=0; i<arr.length; i++){
  return Math.max.apply(Math, arr);
 }
}
maxNum(array) //NaN

Answer

You could use filter and typeof to check for number only.

const array = ['a', 3, 4, 2] // should return 4

function myArrayMax(x) {
  return Math.max(...x.filter(x => typeof x === 'number')); //result is 4
}
console.log(myArrayMax(array)) //4

Using Math.max.apply method

const array = ['a', 3, 4, 2] // should return 4

function myArrayMax(x) {
  return Math.max.apply(null, x.filter(x => typeof x === 'number')); //result is 4
}
console.log(myArrayMax(array)) //4


Source: stackoverflow