Julien Marc Julien Marc - 1 year ago 132
Javascript Question

Underscore sortBy algorithm

I need your help for a little algorithme for my app :

i have an object like this :

var obj = { "response" : [
"candidate" : {
"id":"1",
"price" : 10,
"distance" : 20
},
"candidate" : {
"id":"2"
"price" : 14,
"distance" : 2
},
"candidate" : {
"id":"3",
"price" : 200,
"distance" : 1
}
] }


Which i sort by price like this :

var sortPrice = _(obj.response).sortBy(function(p){
return p.candidate.price
})


It works fine and sort the object (ids) : 1,2,3

Now if candidate has the same price but different distance, i should show first candidate with the same price and the lowest distance :

var obj = { "response" : [
"candidate" : {
"id":"1",
"price" : 10,
"distance" : 20
},
"candidate" : {
"id":"2"
"price" : 10,
"distance" : 2
},
"candidate" : {
"id":"3",
"price" : 200,
"distance" : 1
}
] }

var sorted = _(obj.response).chain().sortBy(function (p) {
return parseInt(p.candidate.price) ;
}).sortBy(function(d){
return parseInt(d.candidate.distance)
}).value();


But it sort me the lowest distance first (ids) : 3(with distance 1), 2(with distance 2), 1(with distance 20) than 2,1,3

Do you have any suggestion?

Thank you.

Answer Source

In pure js you can use sort() like this.

var obj = {
  "response": [{
    "candidate": {
      "id": "1",
      "price": 8,
      "distance": 20
    }
  }, {
    "candidate": {
      "id": "2",
      "price": 8,
      "distance": 2
    }
  }, {
    "candidate": {
      "id": "3",
      "price": 200,
      "distance": 1
    }
  }]
}

obj.response.sort(function(a, b) {
  return a.candidate.price - b.candidate.price || a.candidate.distance - b.candidate.distance;
})

console.log(obj.response)