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?

asked May 26, 2017 at 18:53
1
  • 3
    You need to filter out the none numeric characters first Commented May 26, 2017 at 18:54

3 Answers 3

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);

answered May 26, 2017 at 18:57
3
  • what +s[1] doing here? can you please explain. Commented May 26, 2017 at 19:02
  • I would use something like parseInt() instead. To make the code more readable Commented May 26, 2017 at 19:07
  • @αƞjiβ the + forces the result to be a number, s[1] is second element of string (a string is an array of characters). Commented May 26, 2017 at 19:13
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));

answered May 26, 2017 at 18:57
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]
answered May 26, 2017 at 19:06

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.