Filter by Type
JavaScript
Medium
3 views
Problem Description
You get a JSON array and a type name. Keep only items matching that type (number,string,boolean,null,array,object) and print the resulting JSON array.
Input Format
Line1: JSON array. Line2: type string.
Output Format
One line JSON array.
Sample Test Case
Input:
[1,"a",null,[2],{"x":1},true]
array
Constraints
Type string is one of: number,string,boolean,null,array,object.
Official Solution
const fs=require('fs');const txt=fs.readFileSync(0,'utf8');const lines=txt.split(/\
?\
/);const arrLine=(lines[0]||'').trim();const typeLine=lines.slice(1).join('\
').trim();if(!arrLine||!typeLine)process.exit(0);const arr=JSON.parse(arrLine);const want=typeLine.trim();const match=v=>{if(want==='null')return v===null;if(want==='array')return Array.isArray(v);if(want==='object')return v!==null && typeof v==='object' && !Array.isArray(v);return typeof v===want;};const out=[];for(const v of arr){if(match(v))out.push(v);}process.stdout.write(JSON.stringify(out));
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!