natz0516
natz0516

Reputation: 35

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

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

Upvotes: 0

Views: 1334

Answers (4)

KcH
KcH

Reputation: 3502

//as a note: `isNaN` have weird behaviour .. 

MDN ref: link

const array = ['a', 3, 4, 2] 

let result = Math.max(...(array.filter(el=>!isNaN(el))))

console.log(result)

Upvotes: 0

Always Helping
Always Helping

Reputation: 14570

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

Upvotes: 1

Dalorzo
Dalorzo

Reputation: 20024

I think more efficient could be using array.prototype.reduce:

var result = ['a', 3, 4, 2].reduce( 
      (a,b) => isNaN(a) ? b : (a>=b) ? a : b , 0) ;
console.log(result);

Because it only loops one time the array to get the highest number. The option of filtering and then Math.max will require 2 loops.

Upvotes: 0

Akshay Bande
Akshay Bande

Reputation: 2587

If you wanna ignore strings and only take max from numbers. Math.max accepts numbers, not an array.

let array = ['a', 3, 4, 2] // should return 4
array = array.filter(a => !isNaN(Number(a)));
let max = Math.max(...array);
console.log(max);

Upvotes: 0

Related Questions