Array-Like to Array
JavaScript
Medium
2 views
Problem Description
You get a JSON object having numeric keys and a length. Build a real array of that length. If a key is missing, keep null there. Print the array as JSON.
Input Format
One line JSON object with keys and length.
Output Format
One line JSON array.
Sample Test Case
Input:
{"0":"a","2":"b","length":4}
Output:
["a",null,"b",null]
Official Solution
const fs=require('fs');const s=fs.readFileSync(0,'utf8').trim();if(!s)process.exit(0);const o=JSON.parse(s);const len=Number(o.length||0);let arr=new Array(len).fill(null);for(const k of Object.keys(o)){if(k==='length')continue;const idx=Number(k);if(Number.isInteger(idx) && idx>=0 && idx<len)arr[idx]=o[k];}process.stdout.write(JSON.stringify(arr));
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!