最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

json - Sort javascript array with respect to an attribute - Stack Overflow

matteradmin20PV0评论

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.

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.

Share Improve this question edited Oct 1, 2012 at 9:47 Zlatko 19.6k14 gold badges74 silver badges129 bronze badges asked Oct 1, 2012 at 9:29 GameBuilderGameBuilder 1,1895 gold badges32 silver badges64 bronze badges 7
  • 2 That isn't valid JSON. It isn't even valid JavaScript. – Quentin Commented Oct 1, 2012 at 9:36
  • @Quentin : Fine, I have this DATA and i want to sort by first Name , or roll no using Java Script – GameBuilder Commented Oct 1, 2012 at 9:46
  • It's not really a JSON either, it's an array (and an incorrect one at that, it lacks a ma at the end of the first row). JSON would look like: var data = { rows: [ {"firstname": "joe", "id": 1}, {"firstname": "jack", "id": 2}]}; – Zlatko Commented Oct 1, 2012 at 9: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 Commented Oct 1, 2012 at 9: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 parison function. – Phil H Commented Oct 1, 2012 at 9:52
 |  Show 2 more ments

4 Answers 4

Reset to default 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/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);

});
​

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 parison 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.

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

data.sort(function(a,b) {
    return a.FirstName > b.FirstName;
})

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 parator 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. 

})
Post a comment

comment list (0)

  1. No comments so far