0

I have the following json object and I'm trying to sort it by price.

var data = {"PROPERTY":[
  {"PRICE":456,"NAME":"Test Property 1"},
  {"PRICE":789,"NAME":"Test Property 2"},
  {"PRICE":123,"NAME":"Test Property 3"},
  {"PRICE":654,"NAME":"Test Property 4"},
  {"PRICE":125,"NAME":"Test Property 5"}
]}

Here is the code i'm using to sort.

data.sort(sortByProperty('PRICE'));    

function sortByProperty(property) {
                'use strict';
                return function (a, b) {
                    var sortStatus = 0;
                    if (a[property] < b[property]) {
                        sortStatus = -1;
                    } else if (a[property] > b[property]) {
                        sortStatus = 1;
                    }

                    return sortStatus;
                };
            }

Needless to say the sort is not working. Is it because of the property attribute?

James Privett
  • 1,079
  • 3
  • 15
  • 23
  • 2
    No, it's because `data` object has no `sort` method. – ElmoVanKielmo Jun 05 '14 at 14:17
  • Indeed, @ElmoVanKielmo hit it. You'd need to call `data.PROPERTY.sort(...)` – Brad Christie Jun 05 '14 at 14:19
  • Similar question asked before. See below. http://stackoverflow.com/questions/979256/sorting-an-array-of-javascript-objects – Blaise Jun 05 '14 at 14:21
  • @Blaise - the question you linked has no wrapper object containing the list - and actually this wrapper causes the issue here. OP has prepared the comparison function correctly, so your link will not help. – ElmoVanKielmo Jun 05 '14 at 14:22

1 Answers1

0

Your data object has no sort method - change one line to this:

data['PROPERTY'].sort(sortByProperty('PRICE'));

And the fiddle is here

ElmoVanKielmo
  • 10,907
  • 2
  • 32
  • 46