Normalize to Number or NaN
JavaScript
Medium
5 views
Problem Description
Input is a JSON array with mixed values. Convert each item to a number using Number(). Print a JSON array where invalid conversions become null.
Input Format
One line JSON array.
Output Format
One line JSON array output.
Sample Test Case
Input:
["10"," 5 ",true,"abc",null]
Constraints
Array length up to 1e5.
Official Solution
const fs=require('fs');const s=fs.readFileSync(0,'utf8').trim();if(!s)process.exit(0);const arr=JSON.parse(s);const out=arr.map(v=>{const n=Number(v);return Number.isNaN(n)?null:n;});process.stdout.write(JSON.stringify(out));
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!