Coerce and Sum (Ignore NaN)
JavaScript
Medium
8 views
Problem Description
You get a JSON array. Convert every item with Number(x). Ignore items that become NaN. Sum remaining values and print the sum.
Input Format
One line JSON array.
Output Format
One number output.
Sample Test Case
Input:
["10","abc",true,null,5]
Constraints
Array length up to 2e5.
Official Solution
const fs=require('fs');const s=fs.readFileSync(0,'utf8').trim();if(!s)process.exit(0);const arr=JSON.parse(s);let sum=0;for(const v of arr){const n=Number(v);if(!Number.isNaN(n))sum+=n;}process.stdout.write(String(sum));
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!