简体   繁体   中英

Return a count of the number of strings in the array that can be successfully converted into a number

So I am writing a little function that will return a count of the number of strings in the array that can be successfully converted into a number.

In other words, the string "1" can be successfully converted to the number 1, but the string "hello" cannot be converted into a number.

Here is what I have so far:

 function countNumbers(arr) { var conversion = Number(arr); return conversion; } console.log( countNumbers(['a','b','3','awesome','4']), // 2 countNumbers(['32', '55', 'awesome', 'test', '100']), // 3 countNumbers([]), // 0 countNumbers(['4','1','0','NaN']), // 3 countNumbers(['7', '12', 'a', '', '6', '8', ' ']) // 4 );

Would the Number() function be best suited for this task? Or parseInt() ? Currently it is only returning: NaN NaN 0 NaN NaN , when it should be returning 2 3 0 3 4 .

Use Number() and isNaN like this:

 function countNumbers(arr) { arr = arr.filter(x => x.trim().length !== 0).map(x => x.trim()) const total = arr.reduce((acc, x) => !isNaN(Number(x)) ? acc + 1 : acc, 0) return total; } console.log( countNumbers(['a','b','3','123banana','4']), // 2 countNumbers(['32', '55', 'awesome', 'test', '100']), // 3 countNumbers([]), // 0 countNumbers(['4','1','0','NaN']), // 3 countNumbers(['7', '12', 'a', '', '6', '8', ' ']) // 4 );

Your current implementation makes no attempt to actually count anything, it just hopes Number() will do the exact behavior you want (it doesn't).

Something like this would be fine:

 function countNumbers(arr) { return arr.filter(n => !isNaN(n) && !isNaN(parseInt(n))).length; } console.log( countNumbers(['a','b','3','awesome','4']), // 2 countNumbers(['32', '55', 'awesome', 'test', '100']), // 3 countNumbers([]), // 0 countNumbers(['4','1','0','NaN']), // 3 countNumbers(['7', '12', 'a', '', '6', '8', ' ']), // 4 countNumbers(['123banana','3','',' ',' ','6','3numbers','5']), //3 );

Thanks to @PrashantSharma for the more concise implementation

I use !isNaN(n) && !isNaN(parseInt(n)) because the first one checks that the string is only a number (parseInt thinks 12px is a number for example) and the second discards empty spaces ( '' isn't a number but it passes the first check because... javascript)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM