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
-
3You need to filter out the none numeric characters firststarcorn– starcorn2017年05月26日 18:54:50 +00:00Commented May 26, 2017 at 18:54
3 Answers 3
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
-
what +s[1] doing here? can you please explain.αƞjiβ– αƞjiβ2017年05月26日 19:02:46 +00:00Commented May 26, 2017 at 19:02
-
I would use something like
parseInt()
instead. To make the code more readablestarcorn– starcorn2017年05月26日 19:07:12 +00:00Commented 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).Michał Dąbrowski– Michał Dąbrowski2017年05月26日 19:13:05 +00:00Commented May 26, 2017 at 19:13
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
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]
lang-js