0

I have several products. Each has a specific price and I want a button to sort them by the price.

The products are like this on my site:

<div class="product" id="pr_1">Some Content</div>
<div class="product" id="pr_2">Some Content</div>
<div class="product" id="pr_3">Some Content</div>
...

I parsed the prices from PHP to JavaScript so I have an JavaScript Object containing all prices and product ids:

{12:1, 20:2, 7:3}

Currently the key is the price and the value is the product's id.

I want to have them reordered without reload. So JavaScript / jQuery only. I prefer plain JavaScript.

Is there any way to change the order of the divs according to the prices of the products?

Paul Roub
  • 36,322
  • 27
  • 84
  • 93
Carle B. Navy
  • 1,156
  • 10
  • 28
  • What's happen if two products have same price ? – Samuel Dauzon Dec 07 '15 at 14:20
  • They should be right next to each other, but it doesn't matter which one is first. – Carle B. Navy Dec 07 '15 at 14:21
  • 3
    Ok, but if you use price as key object, it must be unique. Otherwise you get only one product by price. – Samuel Dauzon Dec 07 '15 at 14:22
  • I thought it would be better to take the price as a key, so it is easier to sort the products after the price. But I could do it the other way too. So id would be the key and price the value if it will work that way. – Carle B. Navy Dec 07 '15 at 14:25
  • If you are using JQuery take a look [here](http://stackoverflow.com/questions/881510/sorting-json-by-values) maby it will help you out – Joost Dec 07 '15 at 14:32

2 Answers2

2

You can put your price HTML in a div :

<div id="price_list">

</div>

Then, if you can put your prices in a list like this :

prices = [
  {id:1, price:12},
  {id:2, price:20},
  {id:3, price:7}
];

You'll be able to sort and display with this code :

prices.sort(function(a, b) {
    return parseFloat(a.price) - parseFloat(b.price);
});
// Your array is sorted

$('#price_list').html('');
prices.forEach(function(entry) {
    $('#price_list').append('<div class="product" id="pr_'+entry.id+'">'+entry.price+' dollars</div>');
});

I hope it's fine for you.

If you want a JSFiddle

Samuel Dauzon
  • 10,744
  • 13
  • 61
  • 94
  • Just a side note: the `.sort` prototype doesn't work on `objects`, hence you will have to convert the object to an array if you want to sort it (like the example above, where the list is an `array`). – briosheje Dec 07 '15 at 14:53
0

Sorting by your specification could be done like this Fiddler (note: list is array, not object). However, jedema's answer is the way to go.

`$(document).ready(function() {
  var list = [[1,19], [2,10], [3,5], [4, 22]];

  list.sort(function(a,b) {
      return a[1] - b[1];
  });

  for(i=0;i<list.length;i++){
    var $product = $(".parent").find(".product[data-id=" + list[i][0]+"]");
    $(".newparent").append($product);
  }

});`
Zoran Bosnjak
  • 326
  • 2
  • 8