Exploring the realms of Dynamic Programming to retrieve comprehensive match data

I have developed a basic dynamic program that can retrieve the first matched data. However, I now aim to extract all matched data from my dataset:

let countryList = {
    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'
            }]
        }]
    }]
}

In this dataset, there are two countries with provinces and cities. Users can search for any input like country, province, or city. For instance, searching for Tangail should return all 3 results.

Desired Output:

[{
    name:"Tangail",
    lat: '11'
},{
    name:"Tangail",
    lat: '23'
}, {
    name:"Tangail",
    lat: '112'
}] 

I have attempted the following approach :

function findName(obj, name) {  return obj.name.trim() === name;  }

function information( countryList, searchValue, current, state ) {

   let nextState;  // state is used to prevent call of undefined data
   if ( state === "province" ) {
       nextState = "city";   current = "country";
   } else if( state === "city" ) {
       nextState = "empty";   current = "province";
   } else {
    nextState = "";  current = "city";
   }

   // search matching data
   let data = countryList.find( val => findName( val, searchValue ) );
   // if not data found
   if( typeof data === 'undefined' && nextState !== '' ) {
    let len = countryList.length;  
    for( let x = 0; x < len; x++ ) {  // now search all immediate child data
        let status = {};
        status.name = countryList[x].name;
        status.lebel = current;
        let info;
        info = information(countryList[x][state], searchValue, current, nextState);   // recursive call

        if( typeof info !== 'undefined' ) {  // if data found
            return {  state: status,  data: info };
        }
    }

    // return results;

   } else {
    return data;
   }
 }

let state = "province";
let current = "country";
let searchValue = "Tangail";
let abc = information( countryList.country, searchValue, current, state);
console.log("abc : ", abc);

However, the output always shows the first matched value only.

Any recommendations? Thank you!

Note: This project is implemented in javascript

Answer №1

To begin, transform the data into a list of cities by utilizing the #reduce function. Next, apply the filter method to narrow down the results based on a specific search string. Check out the demonstration provided below for a clearer understanding:

let countryList={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"}]}]}]};
.as-console-wrapper{top:0;max-height:100%!important;}

Answer №2

To preserve your unique style, I suggest implementing a nested approach. Nonetheless, it would be beneficial to use an object for storing the nested array properties and then gather the desired elements in an array.

function findName(obj, name) {
    return obj.name.trim() === name;
}

function information(object, key, search) {
    return object[key].reduce(function (result, element) {
        var temp = findName(element, search);
        if (temp) {
            result.push(element);
            return result;
        }
        if (states[key] && element[states[key]]) {
            return result.concat(information(element, states[key], search));
        }
        return result;
    }, []);
}

var countryList = { 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"...</answer2>
<exanswer2><div class="answer" i="45590807" l="3.0" c="1502271121" m="1502282235" v="1" a="cXFx" ai="1447675">
<p>You could keep your style with the nested approach. But I suggest to use an object for the nested array properties and collect the wanted items in an array.</p>

<p><div>
<div>
<pre class="lang-js"><code>function findName(obj, name) {
    return obj.name.trim() === name;
}

function information(object, key, search) {
    return object[key].reduce(function (r, o) {
        var temp = findName(o, search);
        if (temp) {
            r.push(o);
            return r;
        }
        if (states[key] && o[states[key]]) {
            return r.concat(information(o, states[key], search));
        }
        return r;
    }, []);
}

var countryList = { 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: "Pab...
.as-console-wrapper { max-height: 100% !important; top: 0; }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Shortening a jQuery If-Else Statement in JavaScript

I am working on a snippet of code and need some help. Here is the code: <script type="text/javascript"> $(window).load(function() { if(!$.browser.msie){ $('#myDiv').animate({opacity: 1}, 300); } else if ($.browser.msie) { ...

Python's method of interpolating numpy arrays

Looking for a more efficient method, I want to perform value interpolation on lists by converting them into arrays and then executing the calculations. Currently, I find myself rewriting the formula three times and specifying indexes manually. This is wh ...

Child component not receiving disabled state from Angular 8 FormControl

In my code, there is a unique custom input that I have defined: <nivel-servico-slider formControlName="fornecedor_a"></nivel-servico-slider> This custom input has all the necessary properties as outlined in Angular's guide for c ...

Adjusting font size, contrast, brightness, and sound levels on a website with the help of jQuery

My client has a new requirement: adding functionality to increase font size, adjust contrast/brightness, and control sound on his website. When clicking on any of the control images, a slider should appear for the user to make adjustments accordingly. Ho ...

Can you configure the redux store once and share it across different pages?

I have a redux store where the state is in the form of {names:[], address:[]}. Across multiple pages, both names and address are used as properties. However, I find myself making API calls on each page to fetch these values which is causing unnecessary n ...

The type 'Node' does not have the required attributes

Could anyone shed some light on what might be causing the issue described below? Your insights are greatly appreciated. The problem lies within the line of code: clone = thead.cloneNode(true); The error message reads: 'Type 'Node' is missin ...

Determine the status of all jqXHR requests within an array to confirm completion

My goal is to execute a block of code once all the jqXHR elements in an array have completed, whether they have succeeded or failed. For the full code, you can check it out here: http://jsfiddle.net/Lkjcrdtz/4/ Essentially, I am anticipating the use of t ...

What is the process for displaying images fetched from the API?

Currently, my front-end is built using React/Redux and the API side with AdonisJS. All of my images are stored within the API, and I need to find a way to display them on the front-end. Can anyone provide guidance on accomplishing this task? ...

Unable to update game status using Discord.js setGame() function anymore

For the past 2 months, I've been developing my Discord bot using Discord.JS. However, I recently noticed that the bots I created are not displaying what they are playing as intended. Initially, everything was working fine, but now none of the 3 Discor ...

Switching button class when hovering over another div

When you click on the "collapsible-header" div, I want the text "TE LAAT" in the button to change to "NU BETALEN". Currently, the CSS code changes the text on hover, but I want it to change on click when the collapsible-header also has the active class. T ...

Using jQuery to trigger alert only once variable has been updated

I have a question that may seem too basic, but I can't find the solution. How do I make sure that the variables are updated before triggering the alert? I've heard about using callbacks, but in this case, there are two functions and I'm not ...

After dynamically creating a byte array, an unusual number of symbols appeared in the watch

I would like some clarification on the following behavior: typedef unsigned char byte; byte * test = new byte[8]; I am observing a value of test in the Watch: ÍÍÍÍÍÍÍÍýýýý««««««««îþîþ Why am I seeing 24 symbols instead of jus ...

Is it possible to validate if the file format matches the file name extension using Python or Javascript?

My uploader includes file format validation to only allow certain video formats to be uploaded. However, users could potentially bypass this validation by simply changing the original file name extension (e.g. renaming file.pdf to file.mov and uploading)! ...

Having trouble with the `npm start` command while working with react.js?

Currently, I am in the process of setting up React.js. To achieve this, I executed npm install -g create-react-app followed by create-react-app my-app. Afterward, I proceeded to run the npm start command but encountered the error displayed below. https:// ...

The index array function of PHP's explode algorithm

When using PHP's explode function with the code below $data="test_1, test_2, test_3"; $temp= explode(",",$data); The resulting array looks like this array('0'=>'test_1', '1'=>'test_2', 2='test_3&ap ...

When a new element is introduced, onmouseenter feature assigns a unique dynamic function variable

I am incorporating elements generated by Javascript using a for loop. My goal is to pass different variables to a function for each element. Check out my code snippet: var thumbnail_box = document.createElement("div"); thumbnail_box.onmouseenter = functi ...

Is there a way to create a Multi-set with arrays of a specific length in it?

As a beginner in C++, I am looking to declare a multiset that includes arrays of size 2. The attempt I made seems to be incorrect: multiset<int> nameOfSet[2]; I would appreciate it if someone could clarify what this line is doing. If it's incor ...

Filtering an array in Vue using Lodash based on the values of another array

As I continue to learn JavaScript, I have encountered something that is confusing me. Within my Vue data object, I have the following properties: data: { allergenFilter: [], categoryFilter: [], results: {}, }, I am using an array of check ...

In Chrome, the $http GET request fails to send the JSESSIONID, but it functions properly on Firefox with AngularJS

Here is the code snippet I am working with: $http({ 'method': 'GET', 'url': 'http://www.example.com', 'withCredentials': true, headers: { 'Content-type': &apo ...

Displaying all items in a collection as HTML using Node.js

I am looking to showcase all the items in my mongodb collection as HTML. In the past, I have accomplished this with simpler tasks, such as... router.get('/', function (req, res) { res.render('home', { title: 'Express', u ...