- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Dynamic Programming: return all matched data in JavaScript
Suppose we have a JSON object that have information about the location of some cities of some countries like this −
const countryInfo = { country: [{ name: "Bangladesh", province: [{ name:"Dhaka", city: [{ name:"Tangail", lat: '11' }, { name:"Jamalpur", lat: '12' }] }, { name: "Khulna", city: [{ name:"Jossore", lat: '22' }, { name:"Tangail", lat: '23' }] }, { name: "Rajshahi", city: [{ name:"Pabna", lat: '33' }, { name:"Rangpur", lat: '33' }] }] },{ name: "India", province: [{ name:"West Bengal", city: [{ name:"Calcutta", lat: '111' }, { name:"Tangail", lat: '112' }] }, { name: "Uttar Pradesh", city: [{ name:"Agra", lat: '122' }, { name:"Tajmahal", lat: '123' }] }, { name: "Rajasthan", city: [{ name:"Kanpur", lat: '131' }, { name:"Jaypur", lat: '132' }] }] }] };
We are required to write a JavaScript function that takes in one such object and a search string.
We should then search all the city names matching the search string and return an array of all the city objects that match the query.
Example
The code for this will be −
const countryInfo = { country: [{ name: "Bangladesh", province: [{ name:"Dhaka", city: [{ name:"Tangail", lat: '11' }, { name:"Jamalpur", lat: '12' }] }, { name: "Khulna", city: [{ name:"Jossore", lat: '22' }, { name:"Tangail", lat: '23' }] }, { name: "Rajshahi", city: [{ name:"Pabna", lat: '33' }, { name:"Rangpur", lat: '33' }] }] },{ name: "India", province: [{ name:"West Bengal", city: [{ name:"Calcutta", lat: '111' }, { name:"Tangail", lat: '112' }] }, { name: "Uttar Pradesh", city: [{ name:"Agra", lat: '122' }, { name:"Tajmahal", lat: '123' }] }, { name: "Rajasthan", city: [{ name:"Kanpur", lat: '131' }, { name:"Jaypur", lat: '132' }] }] }] }; const searchForCity = (obj, query) => { const cities = obj.country.reduce((acc, val) => { val.province.forEach(el => { el.city.forEach(elm => { acc.push(elm); }); }); return acc; },[]); const res = cities.filter(el => { return el.name === query; }); return res; }; console.log(searchForCity(countryInfo, 'Tangail'));
Output
The output in the console −
[ { name: 'Tangail', lat: '11' }, { name: 'Tangail', lat: '23' }, { name: 'Tangail', lat: '112' } ]
Advertisements