-2

I would like to know how to order top 3 object array based on price (from max to min) in javascript.

var obj =[{
  id: "1",
  price: 20
},{
  id: "2",
  price: 50,
},{
 id: "3",
 price: 100
},{
  id: "4",
  price: 30
},{
  id: "5",
  price: 80
}]

Expected Output

result = [{
  id: "3",
  price: 100
 },{
  id: "5",
  price: 80
},{
  id: "2",
  price: 50,
}]
miyavv
  • 763
  • 3
  • 12
  • 30
  • Why not use sort? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort – keysl Jan 21 '20 at 02:18

1 Answers1

1

Can be easily achieved with Array.prototype.sort().

This function returns a sorted array, and does not change the original.

var obj =[{
  id: "1",
  price: 20
},{
  id: "2",
  price: 50,
},{
 id: "3",
 price: 100
},{
  id: "4",
  price: 30
},{
  id: "5",
  price: 80
}]

function compare(a, b) {
  if(a.price > b.price)
     return 1;
  if(a.price < b.price)
     return -1;
  // Equals
  return 0;
}

var sorted = obj.sort(compare);

Check the results and you might need to switch between the return 1 and return -1. I honestly never remember which is ascending or descending :facepalm:

Now, if you wanna get the top 3 simply slice the array

var top3 = sorted.slice(0, 3);
fingeron
  • 1,152
  • 1
  • 9
  • 20