Search code examples
javascriptsortingdynamic-arrays

How to sort an array which is created by joining two different arrays in javascript


I am creating an array of results which is formed by joining the arrays from two different requests. The results have "Places" and "Addresses". I am separating "Places" and "Addresses" and showing them up but I wanted to display places first and then address. Can any one please help. below is my code -

        let results_html = [];

        results_places = ['<li style="margin: 12px"><i style="display:block;float:left" class="material-icons">place</i><span style="font-size:1.25em;font-size: 20px">Places</span></li>']
        results_addresses = ['<li style="margin: 12px"><i style="display:block;float:left;font-size: 20px" class="material-icons">home</i><span style="font-size:1.25em">Addresses</span></li>']

        if (predictions && predictions.length) {
          // debugger;
          if (predictions[0].types.join().indexOf("postal_code")!=-1 || predictions[0].types.join().indexOf("locality")!=-1) {

            results_html.push(results_places);

          } else if(predictions[0].types.join().indexOf("health")!=-1|| predictions[0].types.join().indexOf("hospital")!=-1 || predictions[0].types.join().indexOf("route")!=-1 || predictions[0].types.join().indexOf("premise")!=-1 || predictions[0].types.join().indexOf("street_address")!=-1) {

            results_html.push(results_addresses);

          }

          predictions.forEach(function (prediction) {
            results_html.push(`<li class="autocomplete-item" data-type="place" data-place-id=${prediction.place_id}>      
                                    <span class="autocomplete-text">${prediction.description}</span></li>`);


          });
        }

        if (predictions2) {

          if (predictions2[0].types.join().indexOf("postal_code")!=-1 || predictions2[0].types.join().indexOf("locality")!=-1) {

            results_html.push(results_places);

          } else if(predictions2[0].types.join().indexOf("health")!=-1|| predictions2[0].types.join().indexOf("hospital")!=-1 || predictions2[0].types.join().indexOf("route")!=-1 || predictions2[0].types.join().indexOf("premise")!=-1 || predictions2[0].types.join().indexOf("street_address")!=-1) {

            results_html.push(results_addresses);

          }

          predictions2.forEach(function (prediction) {
            results_html.push(`<li class="autocomplete-item" data-type="place" data-place-id=${prediction.place_id}>      
                                    <span class="autocomplete-text">${prediction.description}</span></li>`);
           });
        }

        autocomplete_results.innerHTML = results_html.join("");

Here is the current output -

enter image description here


Solution

  • I have looked into your code just edit this line to

    let displaySuggestions = function (predictions2, predictions) 
    

    here is jsfiddle