What is the best way to isolate a single element within a for loop and exclude all others?

I have implemented a dynamic Ajax call to compare the string entered in the text field (representing a city name) with the "type" value in a JSON array.

As I iterate through the elements of the array, I am checking the values associated with the key "type" to include both cities with a type equal to "city" and those with a type equal to "hamlet".

To prevent duplicate indexing for cities that have both types present, I need to exclude them from being displayed multiple times in the search results.

The Ajax call is as follows:

$.ajax({
  url: "https://nominatim.openstreetmap.org/search?q=" + encodeURIComponent($("#inlineFormInputCitta").val()) + "&format=geocodejson",
  dataType: "json",

  success: function(data) {
    var check = false;
    for (let i = 0; i < data.features.length; i++) {
      let typeCity = data.features[i].properties.geocoding.type;
      if (typeCity === "city") {
        let nameCity = data.features[i].properties.geocoding.name;
        for (let i = 0; i < francigena.tappe.length; i++) {
          let tappa = francigena.tappe[i];
          let city = francigena.tappe[i].city;
          let fs = francigena.tappe[i].fs;

          if (city === nameCity && fs === "true") {
            check = true;
            $('#tabellaEconteuti').show();

          } else if (city === nameCity) {
            check = true;
            console.log("JSON file has been activated");
            $('#tabellaEconteuti').show();

            $("#tbody").append("<tr><td>" + tappa.name + "</td><td>" + tappa.state + "</td><td>" + tappa.region + "</td><td>" + tappa.city + "</td></tr>");
            $("#tabella").show();
          }
        };
      };
    }


    if (
      !check
    ) {
      $('#myModal').modal('show');
    }
  },
}

The goal is to customize the search by associating user input with the API query URL. However, due to the presence of some cities listed under both "city" and "hamlet" types, there is a concern about duplicates in the search results.

A new method using Set() has been tried:

success: function(data) {
    var check = false;
    var cityList = new Set()
    for (let i = 0; i < data.features.length; i++) {
        let typeCity = data.features[i].properties.geocoding.type;
        if (typeCity === "hamlet") {
            let nameCity = data.features[i].properties.geocoding.name;
            for (let i = 0; i < francigena.tappe.length; i++) {
                let tappa = francigena.tappe[i];
                let city = francigena.tappe[i].city;
                let fs = francigena.tappe[i].fs;
                if (city === nameCity && fs === "true") {
                    check = true;
                    console.log("'fs' === 'true' has been activated");
                    $('#tabellaEconteuti').show();
                    $("#tabella").show();
                } else if (city === nameCity) {
                    check = true;
                    console.log("JSON file has been activated");
                    $('#tabellaEconteuti').show();
                }
                if (cityList.has(city)) {
                    continue
                }
                cityList.add(city);
                if (typeCity === "city") {
                    let tappa = francigena.tappe[i];
                    let city = francigena.tappe[i].city;
                    let fs = francigena.tappe[i].fs;
                    if (city === nameCity && fs === "true") {
                        check = true;
                        console.log("'fs' === 'true' has been activated");
                        $('#tabellaEconteuti').show();
                        $('#TrenitaliaButton').on('click', showTrenitaliaInfo);
                    } else if (city === nameCity) {
                        check = true;
                        console.log("JSON file has been activated");
                        $('#tabellaEconteuti').show();
                    }
                }
            }
        } {
            ...    
        };
    }
    if (!check) {
        $('#tabellaEconteuti').hide();
    }
},

Despite attempting to use the Set() method, there were still issues with redundant listings for certain cities. Further adjustments are needed to achieve the desired outcome without duplications.

  • -EDIT-

Considering an alternative approach, I aim to leverage the following steps:

1) Identify when the "type" value is "city" and set a flag variable A accordingly.

2) Implement a separate loop to handle cases where the "type" value is "hamlet".

This strategy seems more straightforward and could aid in resolving the duplication problem efficiently. How can I effectively implement this logic?

Answer №1

Opting for a Set over an Array would be the more appropriate decision in this scenario. The process involves checking each city to see if it already exists in cityList. If it does, the code moves on to the next city; otherwise, the city is added to cityList before proceeding.

A similar check should be performed for the other array.

var check = false; 
var cityList = new Set()
for (let i = 0; i < data.features.length; i++) {
    let typeCity = data.features[i].properties.geocoding.type;
    if (typeCity === "city") {
        let nameCity = data.features[i].properties.geocoding.name;
        for (let i = 0; i < francigena.tappe.length; i++) {
            let tappa = francigena.tappe[i];
            let city = francigena.tappe[i].city;
            let fs = francigena.tappe[i].fs;

            if (cityList.has(city)) {
                continue;
            }
            cityList.add(city);

            if (city === nameCity && fs === "true") {
                check = true;                                       
                $('#tabellaEconteuti').show(); 

            } else if (city === nameCity) {
                check = true;
                console.log("JSON file has been activated");                                       
                $('#tabellaEconteuti').show();

                $("#tbody").append("<tr><td>" + tappa.name + "</td><td>" + tappa.state + "</td><td>" + tappa.region + "</td><td>" + tappa.city + "</td></tr>");    
                $("#tabella").show();                                        
            }
        }
    }
}

Answer №2

In order to solve the issue, I implemented a solution utilizing a boolean variable called locationFound along with a break statement to exit the loop.

Initially, I set the variable to false outside of the for loop, making sure it was in place before the cycle began. During the loop execution, I updated the variable to true and executed certain actions followed by a break statement to break out of the loop once the desired value was found.

Furthermore, I included a condition within an if statement outside of the for loop where I set the variable back to false. Subsequent actions were then performed, leading to another break statement which allowed me to exit the loop upon finding the required value. This approach yielded the expected results without any duplicates:

$.ajax({
        url: "https://nominatim.openstreetmap.org/search?q=" + encodeURIComponent($("#inlineFormInputCitta").val()) + "&format=geocodejson",
        dataType: "json",            

        success: function (data) {                

            for (let i = 0; i < data.features.length; i++) {

                var locationFound = false; //Initializing the boolean variable as false
                let typeCity = data.features[i].properties.geocoding.type;

                if (typeCity === "city") {
                    locationFound = true;  //Setting the boolean variable to true and performing necessary actions

                    break;    // Exiting the loop
                    }

                else if (locationFound === false) {
                    if (typeCity === "hamlet") {
                        var locationFound = true; //Updating the boolean variable to true and executing subsequent actions
                        //Displaying the table
                        break;   //Exiting the loop                         
                    }
                }

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

Pressing the "Enter" key will submit the contents of

Hello, I have recently created a new chat box and everything seems to be working fine. However, I am facing an issue with submitting a message when I press enter (to go to the function Kucaj()). Can anyone provide assistance with this problem? I tried ad ...

The hyperlinks in the navigation bar are leading me to incorrect destinations

I am currently developing an authentication app and facing an issue with the navbar links for register and login. They are not redirecting me to the correct destination. These links work perfectly on the landing index page, but not on any other page. site ...

What is preventing me from using javascript setInterval with a function in a separate external file?

Everything is running smoothly with this code snippet...an alert pops up every 10 seconds <script type='text/javascript'> function letsTest(){ alert("it works"); } var uptimeId = window.setInterval(letsTest, 10000); < ...

The solution for fixing contenteditable is as follows:

I am currently working on a script to clean up pasted text within a contenteditable div. While the script is functioning well for most part, I have noticed that in Firefox, line breaks get removed when the text is copied within or between the divs. Does ...

Update and verify a collection of objects in real-time

I have a callback function that retrieves a data object from the DOM. Each time an item is selected, the function returns an object like this: $scope.fClick = function( data ) { $scope.x = data; } When ...

Updating the handler function for AutoComplete with Checkbox in Material UI using React JS

I am looking to include an <AutoComplete /> field in my form. The options for this field are fetched through a get request, and here is the result displayed in the console. [ { "uid": "c34bb0ed-9f63-4803-8639-a42c7e2a8fb0&q ...

Error encountered while sending a post request from Angular to NodeJS with JSON data

When making a POST request to a NodeJS app from Angular, the request code in Angular is as follows: export class SearchComponent { constructor(private http: HttpClient) {} newWord = ''; keyword = ''; onClick() { const head ...

C# - Issue with Webbrowser failing to fully load pages

I am facing an issue with loading pages completely on the web browser, likely due to heavy usage of JavaScript. To address this problem, I have integrated another browser into the project called Awesomium. I am wondering if Awesomium supports using getEle ...

Getting a list of users from Parse in an Android app is a straightforward process

Our team is in the process of developing push notification functionality for Android. We have successfully implemented sending push notifications between three mobile devices. However, we now face the challenge of retrieving a list of users from Parse. Des ...

Tips for resolving the Angular Firebase v.7 problem: The search for '_delegate' in the users/xxxxx cannot be conducted using the 'in' operator

I'm working on implementing the new Angular Firebase v.7 with Angular and encountering an error message: Cannot use 'in' operator to search for '_delegate' in users/1QAvZYg6aqe0GhA13tmVAINa. While I found a similar question ( Fire ...

VueJS does not support certain characters in its JavaScript replace function

In my current situation, I am utilizing the replace method in the following manner: <code v-html="'/<try>/'.replace(/(?:\r\n|\r|\n)/g, 'testing')"></code> As I work with a longer string t ...

How do I retrieve the id of an event using a class descriptor within a JQuery Dialog constructor in Javascript?

As someone who is relatively new to JavaScript and jQuery, I must apologize in advance if my question seems basic. :) In a straightforward webpage, I am utilizing JQuery UI's Tabs and attempting to implement a double-click feature on the Tab names th ...

Peculiar redirection encountered while handling a form with checkbox option

When I try to submit the form in Chrome, the PHP file does not get called and I am redirected to another HTML page. However, in Firefox, when I select three checkboxes, it redirects me to that same HTML page as in Chrome. I even tried using radio buttons i ...

What causes the return of undefined when accessing an item from an object?

In order to extract the item "Errors" from the data object provided below: {Id: 15, Date: "22-02-2019", Time: "22:45", Sport: "Football", Country: "United Kingdom", …} Bet: "Win" Bookie: "Bet365" Competition: "Premier League" Country: "U ...

What is the best way to retrieve the value stored in a variable?

In my Node.js program, I have a snippet of code where I am working with a map named `transMap`. My goal is to retrieve the value for 'yy', which should be "ipaddress", and then output it as JSON. While I expected the JSON response to be { "ipaddr ...

Instructions on removing an HTML element from a div that has the attribute contentEditable

Here is an example of HTML code: <div id="editable" contentEditable="true"> <span contentEditable="false">Text to remove</span> </div> I want to be able to delete the entire span element (along with its text) with just one bac ...

When scrolling, dynamically change the background color by adding a class

I am looking to achieve a scroll effect where the color of the menu buttons changes. Perhaps by adding a class when scrolling and hitting the element? Each menu button and corresponding div has a unique ID. Can anyone suggest what JavaScript code I should ...

Decoding a JSON array API response in Golang: A step-by-step guide

I have been attempting to extract data from Wikipedia's API at https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article/en.wikipedia.org/all-access/all-agents/Smithsonian_Institution/daily/20160101/20170101 and convert it into an array of struc ...

Validation of the JSON schema has encountered an error. The value in the array does not meet the requirement as it should be either a null or an object. This issue has been identified in

Summary: I encountered an error message regarding JSON schema validation when working with a custom HTTPS Sample Request payload that includes arrays. The error specifically states that the array requires an object or null value, but found an array instea ...

Transferring checkbox data to Bootstrap modals and dynamically summoning specific div modals using their unique identifiers

I have been trying to populate the checkbox values into corresponding modal divs based on button clicks, but I am facing difficulties in achieving it. Desired outcome: The buttons should trigger the display of selected checkbox values in their respective ...