1

I have an array like ['VS', 'V1', 'V2', 'V3', 'VE']

I am using substring to get second part which returns me 'S', '1', '2', '3', 'E'

I have to find the max integer value which will be 3 in this case. I tried this solution but I am geting NaN.

Any suggestion?

αƞjiβ
  • 3,056
  • 14
  • 58
  • 95

3 Answers3

4

You could check the casted value for truthyness and use a zero as default value.

+s[1] || 0

 s[1]       take the character at index 1
+           use unary plus for converting string to number, this could return NaN
      || 0  in this case take zero instead of the falsey value, like NaN

var array = ['VS', 'V1', 'V2', 'V3', 'VE'],
    max = Math.max(...array.map(s => +s[1] || 0));

console.log(max);

ES5

var array = ['VS', 'V1', 'V2', 'V3', 'VE'],
    max = Math.max.apply(null, array.map(function (s) { return +s[1] || 0; }));

console.log(max);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

The issue is that the values are still strings after you get rid of the first char.

var ary = ['VS', 'V1', 'V2', 'V3', 'VE'];

var ary2 = ary.map(function(val){
  // Get the second character and convert to a number if possible
  // ruturn that number or null
  return parseInt(val.charAt(1)) || null;
});

// Now, the function will work
Array.max = function( array ){
    return Math.max.apply( Math, array );
};

console.log(Array.max(ary2));
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
0

You may want to remove any non-numbers. This should return an array containing only numbers of your array.

['S','1','2','3','E'].filter((item) => parseInt(item)).map((item) => parseInt(item))

will return:

 [1, 2, 3]
Alon
  • 57
  • 1
  • 7