1

I am new to JSON and Javasript.

I have data in JSON

var data = [
"FirstName: 'xyz', Lastname 'QSD', rollNo:'1',EntryDate:'2012-09-11T17:35:31.835+02:00'"

"FirstName: 'abc', Lastname 'qgr', rollNo:'2',EntryDate:'2012-08-11T17:35:31.835+02:00'"

]

I want to sort it according to FirstName ,or by roll no or any other attribute i choose.

Thanks in advance.

Zlatko
  • 18,936
  • 14
  • 70
  • 123
GameBuilder
  • 1,169
  • 4
  • 31
  • 62
  • 2
    That isn't valid JSON. It isn't even valid JavaScript. – Quentin Oct 01 '12 at 09:36
  • @Quentin : Fine, I have this DATA and i want to sort by first Name , or roll no using Java Script – GameBuilder Oct 01 '12 at 09:46
  • It's not really a JSON either, it's an array (and an incorrect one at that, it lacks a comma at the end of the first row). JSON would look like: var data = { rows: [ {"firstname": "joe", "id": 1}, {"firstname": "jack", "id": 2}]}; – Zlatko Oct 01 '12 at 09:49
  • @GameBuilder — You can either write a custom parser for it (which is somewhat too large a problem to walk through all the steps of in a StackOverflow answer) or you can fix the data. – Quentin Oct 01 '12 at 09:50
  • Or see my answer. With a bit of formatting the strings can be parsed as JSON (it's very close, despite the criticisms above), and then sorted with a comparison function. – Phil H Oct 01 '12 at 09:52
  • See this - http://stackoverflow.com/questions/979256/how-to-sort-an-array-of-javascript-objects – web-nomad Oct 01 '12 at 10:10
  • @Pushpesh — Why? It isn't an array of objects. – Quentin Oct 01 '12 at 10:12

4 Answers4

4

Since you tagged the question as dojo, here is the dojo way via dojo/store/Memory. There is also a tutorial to Dojo Object Store.

See the code below in action at jsFiddle: http://jsfiddle.net/phusick/MGUBT/

require(["dojo/store/Memory"], function(Memory) {

    var data = [
        { FirstName: 'xyz', Lastname: 'QSD', rollNo: '1', EntryDate: '2012-09-11T17:35:31.835+02:00' },
        { FirstName: 'abc', Lastname: 'qgr', rollNo: '2', EntryDate: '2012-08-11T17:35:31.835+02:00' }
    ];

    var store = new Memory({ data: data });

    var sortedData = store.query(null, {
        sort:[{ attribute: "FirstName", descending: false }]
    });

    console.dir(sortedData);

});
​
phusick
  • 7,342
  • 1
  • 21
  • 26
2

If datais supposed to be an array containing objects, you could do:

data.sort(function(a,b) {
    return a.FirstName > b.FirstName;
})
David Hellsing
  • 106,495
  • 44
  • 176
  • 212
  • That's not what the function is supposed to return, which is a number. – Prinzhorn Oct 01 '12 at 09:38
  • Ok then `(a.FirstName>b.FirstName)*1`, but it should be the same. – David Hellsing Oct 01 '12 at 09:41
  • **It's not**. comparison is **ternary** (smaller, equal, greater), that's why you need a number that is smaller, equal or greater than zero (usually -1, 0 and 1). When a is smaller than b, you return 0! – Prinzhorn Oct 01 '12 at 09:44
  • @Prinzhorn But it will work anyway 'cause it will compare the first letters according to each ascii value; `A=65, B=66, Z=90, a=97,...` - at least i think it's the ascii value? – Andreas Louv Oct 01 '12 at 09:44
  • @Prinzhorn: the boolean returned by the callback is coerced to a number anyways, David's original answer works just fine, though admittedly MDN does suggest `return a.property > b.property ? 1 : -1;` – Elias Van Ootegem Oct 01 '12 at 09:46
  • @Prinzhorn `localeCompare()` is not browser-proof, so I don’t use it. You could write `((x < y) ? 1 : ((x > y) ? -1 : 0));` etc, but I don’t think it’s necessary here. – David Hellsing Oct 01 '12 at 09:50
  • 1
    Why do we even argue: http://www.allenpike.com/2009/arraysort-browser-differences/ – Prinzhorn Oct 01 '12 at 09:57
2

The first problem is the structure of your data. You have effectively an array like

var data = [ "foo", "bar" ];

and these lines of strings contain serialized data. So first we need to extract the data via any method given in this SO question, for example the JSON library method:

var interpreted = [];
for(var i=0; i<data.length; ++i) {
    interpreted[i] = JSON.parse(data[i]);
}

Now we have structures like this:

[
    0: {
        'Firstname': 'xyz',
        'Lastname' : 'QSD', // there is a colon missing in the
                            // source, I'm guessing accidentally
        ...
    },
    1: {
        'Firstname' : 'abc',
        ...
    }
]

So we can access the firstname via interpreted[i].Firstname. Now we can sort in a similar way to this other SO question, by passing sort() a comparison function:

interpreted.sort(function(a,b) { 
    if(a.Firstname == b.Firstname)
        return 0;
    if(a.Firstname > b.Firstname)
        return 1;
    else
        return -1
} );

Where you need to swap 1 and -1 if you want to sort descending.

Community
  • 1
  • 1
Phil H
  • 19,928
  • 7
  • 68
  • 105
0

Your first problem is that the members are string literals, not objects. But as long as they are written as they are now, you can just use a simple sort. Just write

data.sort();

and the array will be sorted by first name.

What you want is something like:

var data = [
 {FirstName: 'xyz', Lastname 'QSD', rollNo:'1',EntryDate:'2012-09-11T17:35:31.835+02:00'},
 {FirstName: 'abc', Lastname 'qgr', rollNo:'2',EntryDate:'2012-08-11T17:35:31.835+02:00'}
]

You can then sort using the sort() function providing your own comparator like this:

data.sort(function (a, b) {
    return // return a positive number if a > b
           // use a.FirstName to access value of FirstName in a. 

})
Eivind Eidheim Elseth
  • 2,294
  • 1
  • 23
  • 28