-2

I have created an array.

sample:

[
  { 
    title: "RandomTitle",
    distance: 600
  },
  { 
    title: "RandomTitle",
    distance: 480
  },
  { 
    title: "RandomTitle",
    distance: 500
  }
]

Is it possible to get the objects in the array to be sorted based on the lowest distance value to the highest?

I am making a for loop where I display content in a div and I want it to show the nearest locations to users input.

lite version of my code: http://codepen.io/anon/pen/MKwqMv?editors=101

Christian4423
  • 1,746
  • 2
  • 15
  • 25
  • possible duplicate of https://stackoverflow.com/questions/979256/sorting-an-array-of-javascript-objects – Lil Devil Dec 10 '15 at 19:58
  • There are multiple SO answers that deal with this, and the Array.sort documentation covers almost exactly this example. – Rob Foley Dec 10 '15 at 19:59
  • arrgh. it is an array of *objects*, not "JSON objects" (whatever that is) – npup Dec 10 '15 at 20:57

2 Answers2

2

Yeah, just define a proper sort compare function:

var obj = [{
  name: "RandomTitle",
  distance: 600
}, {
  name: "RandomTitle",
  distance: 480
}, {
  name: "RandomTitle",
  distance: 500
}];

obj.sort(function(a,b){return a.distance - b.distance}); // this is the key

$(function() {
  for (var i = 0; i < 3; i++) {
    DOMresults = $("#unordered-list");
    name = obj[i].name;
    distance = obj[i].distance;
    console.log(obj)

    resultsContent = '<li><p>Name: ' + name + '</p><p>Distance: ' + distance + '</p></li>';
DOMresults.append(resultsContent)
  };

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="unordered-list">

</ul>
Shomz
  • 37,421
  • 4
  • 57
  • 85
0

Yes, use the sort function. Assuming that your array is stored in the "arr" var you should have something like

arr.sort(function(obj1, obj2) {
   // obj1 and obj2 will be arr[0] and arr[1] at the first iteration, 
   // arr[1] and arr[2] on the second, etc
   return ... // here you compare your objects, read the sort documentation provided in the link above.
});
BrunoRB
  • 889
  • 8
  • 14