最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - Jquery each sort by value - Stack Overflow

matteradmin4PV0评论

I'm currently trying to create a store locator. My current code grabs the stores information from an xml file, then if it's in the given radius it will place it inside a div.

My problem is that it just adds the stores in the order their in inside the xml. So in my case it's alphabetical. There are 4 values for each store Name, Address, website, and then the distance.

What I want to be able to do is place them in the div in order from the shortest distance to longest. How can I do that?

Here's the code

function searchxml(origin, rad) {
$(data).find("marker").each(function () {
    var $marker = $(this);
    var name = $marker.attr("name");
    var website = $marker.attr("website");
    var address = $marker.attr("address").replace('&lt;', '<').replace('&gt;', '>');
    var lat = $marker.attr("lat");
    var lng = $marker.attr("lng");
    var latlng = new google.maps.LatLng(lat, lng);
    var destination = new google.maps.LatLng(lat, lng);
    var distance = google.maps.geometry.sphericalputeDistanceBetween(origin, destination);

    var miles = Math.round(distance * 0.000621371192);
    if (miles <= rad) {
        $('#storeInfo').prepend('<div class="storeLocation"><div class="storeLeft"><span class="storeTitle">' + name + '</span></br><p class="storeAddress">' + address + '</p><a href="' + website + '">' + website + '</a></div><div class="storeRight"><span class="storeDistance">Distance: ' + miles + ' miles</span><a href="=' + address + '&daddr=' + origin + '"  class="storeDirections">Map It</span></div><div class="clear"></div></div>').html();
        $('#map_canvas').gmap('addMarker', {
            'position': destination,
            'bounds': true
        }).click(function () {
            $('#map_canvas').gmap('openInfoWindow', {
                'content': name + '<br/>' + address
            }, this);
        });
    } else {}
});
}

I'm currently trying to create a store locator. My current code grabs the stores information from an xml file, then if it's in the given radius it will place it inside a div.

My problem is that it just adds the stores in the order their in inside the xml. So in my case it's alphabetical. There are 4 values for each store Name, Address, website, and then the distance.

What I want to be able to do is place them in the div in order from the shortest distance to longest. How can I do that?

Here's the code

function searchxml(origin, rad) {
$(data).find("marker").each(function () {
    var $marker = $(this);
    var name = $marker.attr("name");
    var website = $marker.attr("website");
    var address = $marker.attr("address").replace('&lt;', '<').replace('&gt;', '>');
    var lat = $marker.attr("lat");
    var lng = $marker.attr("lng");
    var latlng = new google.maps.LatLng(lat, lng);
    var destination = new google.maps.LatLng(lat, lng);
    var distance = google.maps.geometry.spherical.puteDistanceBetween(origin, destination);

    var miles = Math.round(distance * 0.000621371192);
    if (miles <= rad) {
        $('#storeInfo').prepend('<div class="storeLocation"><div class="storeLeft"><span class="storeTitle">' + name + '</span></br><p class="storeAddress">' + address + '</p><a href="' + website + '">' + website + '</a></div><div class="storeRight"><span class="storeDistance">Distance: ' + miles + ' miles</span><a href="http://maps.google./maps?saddr=' + address + '&daddr=' + origin + '"  class="storeDirections">Map It</span></div><div class="clear"></div></div>').html();
        $('#map_canvas').gmap('addMarker', {
            'position': destination,
            'bounds': true
        }).click(function () {
            $('#map_canvas').gmap('openInfoWindow', {
                'content': name + '<br/>' + address
            }, this);
        });
    } else {}
});
}
Share Improve this question edited Mar 27, 2012 at 20:40 Engineer 48.9k12 gold badges90 silver badges92 bronze badges asked Mar 27, 2012 at 20:23 poergpoerg 1571 gold badge2 silver badges11 bronze badges 1
  • Use a custom sort function that pares the distances... – mowwwalker Commented Mar 27, 2012 at 20:25
Add a ment  | 

2 Answers 2

Reset to default 2

Instead of just appending the new divs you create where you are (i.e. on the line $('#storeInfo').prepend(...), you could store them in an array together with their distance from the location, then sort this array by the distance and finally add these new divs to the storeInfo element in the sorted order.

e.g.

function searchxml(origin, rad) {
  var stores = []; //array which will store divs and the distances..
  $(data).find("marker").each(function () {
      ...
     if (miles <= rad) {
        var div = $('<div class="storeLocation"> ...');
        //don't just add this straight away..
        //store it in a simple object holding the new div
        //and the distance and push it onto the array.. 
        stores.push({ div: div, miles: miles });

       $('#map_canvas').gmap('addMarker', {
          ...
    } else {}
  });

  //sort to get the right order..
  stores.sort(function(a,b){
      return b.miles - a.miles; //smaller is better..
  });
  //now append them in the sorted order..
  var storeInfo = $('#storeInfo');
  $.each(stores, function(store){
      storeInfo.append(store.div);
  });
}

Note: here I've used ... to indicate where you should put what's in you code already in an attempt to make the changes easier to see.

What I would do is create a custom sort method (you can either extend jQuery or create a method outside of the framework, makes no difference), and then store your values in an array, sort them, then place them into your container.

function sortByDistance(a, b) {
    var x = a.distance;
    var y = b.distance;
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}

So, then you have your array of items, say var arr = [], and to call it:

var arr = [];
// add your items arr.push(..item..);
arr.sort(sortByDistance);

Obviously you have two ways you can go about doing this. You can create a custom object with all your values in it, put each into the array and then run the sorting method, or you can simply push all your values to an array, call the sort and then do the plicated logic inside the sort method.

Hope this helps! (I started writing the plete code, but then I figured I was spending too much time and you probably have your own way of writing your code).

Post a comment

comment list (0)

  1. No comments so far